Goldn123 Goldn123 - 7 months ago 28
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; 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;

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)

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.


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

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


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.