Goldn123 Goldn123 - 3 months ago 10
PowerShell Question

Script not running first time in console, does afterwards

Hoping you can help as I have run out of ideas and at this point I think it is because I don't understand PowerShell properly.

I read this series; https://foxdeploy.com/2016/05/17/part-v-powershell-guis-responsive-apps-with-progress-bars/ and tried to do the same thing, then I discovered that I could not call my script by opening a normal PowerShell console (Not ISE) and doing .\script.ps1

I also noticed that I could not do the same with the example script located here;

https://github.com/1RedOne/BlogPosts/blob/master/GUI%20Part%20V/PowerShell_GUI_Template.ps1

It does run the SECOND time however and every time after that? For example if you do

.\script.ps1 (doesn't work)
.\script.ps1 (works)
.\script.ps1 (works)
etc...


But if you do

powershell .\script.ps1 (doesn't work)
powershell .\script.ps1 (doesn't work)


However if you close ISE, open it again and run script it works first time?

I don't really know what is causing this.

Does anyone have any ideas?

If you would like to see this just copy from github link as that one has same problem as mine.

Answer

The issue is due to line 39-41 in the script on GitHub:

$syncHash.Window=[Windows.Markup.XamlReader]::Load( $reader )

[void][System.Reflection.Assembly]::LoadWithPartialName('presentationframework')

As you can see, presentationframework.dll is not being loaded into the appdomain until after XamlReader.Load() is being called.

The entire rest of the script is dependant on the output from this call, so the entire thing fails.

Second time around, the presentationframework assembly has already been loaded, so the call succeeds and the Window is created correctly.

Comments