Search This Blog

Thursday, March 07, 2013

Powershell scripts and .Net assemblies–force PS to run later .Net CLR

Recently i was writing a PS script to check a list of websites. To do this I was using a .net class

HttpWebRequest


So I wrote the script in powerGUI on the server where I wanted the script to run. I got it working within powerGUI, so I thought I would then schedule the script.



But when I run the script from the tesk scheduler I was met with an error, stating that one of the objects I wanted to use didnot contain a method.




Method invocation failed because [System.Net.HttpWebResponse] doesn't contain a method named 'Dispose'.




What?!, it worked fine in the powerGUI on the same server.



Anyway I eventually tracked this down to the fact that powershell 2.0 starts with an older .Net framework CLR. So I needed to get powershell to run a later version.



I found an article here, it explains the problem and the solutions nicely.



http://viziblr.com/news/2012/5/16/the-easy-way-to-run-powershell-20-using-net-framework-40.html



I created the xml files in the locations specified and it solved my problems.



C:\Windows\System32\WindowsPowerShell\v1.0




  • powershell.exe.config


  • powershell_ise.exe.config



XML contents




<?xml version="1.0"?>

<configuration>


    <startup useLegacyV2RuntimeActivationPolicy="true">


        <supportedRuntime version="v4.0.30319"/>


        <supportedRuntime version="v2.0.50727"/>


    </startup>


</configuration>


Share/Bookmark

2 comments:

  1. What a fantastic perspective! I appreciate the positivity and motivation you bring to your writing. Looking forward to more!

    ReplyDelete
  2. This loads a specific .NET Domain esia assembly, which ensures PowerShell uses the CLR version associated with that assembly.






    ReplyDelete