0

I am trying to create a GUI page with powershell. The script works fine with powershell version 4.0 . But it throws exception when tried to execute it in poweshell version 3.0

$return = button "Enter Parameters" "Enter Domain" "Enter User" "Enter Server" 
function button ($title,$domain, $user, $Server) { 

[void][System.Reflection.Assembly]::LoadWithPartialName( "System.Windows.Forms")  
[void][System.Reflection.Assembly]::LoadWithPartialName( "Microsoft.VisualBasic")  


$form = New-Object "System.Windows.Forms.Form"; 
$form.Width = 500; 
$form.Height = 150; 
$form.Text = $title; 
$form.StartPosition = [System.Windows.Forms.FormStartPosition]::CenterScreen; 

$textLabel1 = New-Object "System.Windows.Forms.Label"; 
$textLabel1.Left = 25; 
$textLabel1.Top = 15; 

Exception:

At C:\Users\rights.ps1:16 char:35
+ [void][System.Reflection.Assembly]LoadWithPartialName( System.Windows.Forms)
+                                   ~~~~~~~~~~~~~~~~~~~
Unexpected token 'LoadWithPartialName' in expression or statement.
At C:\Users\rights.ps1:17 char:35
+ [void][System.Reflection.Assembly]LoadWithPartialName( Microsoft.VisualBasic)
+                                   ~~~~~~~~~~~~~~~~~~~
Unexpected token 'LoadWithPartialName' in expression or statement.
At C:\Users\rights.ps1:23 char:67
+     $form.StartPosition = [System.Windows.Forms.FormStartPosition]CenterScreen;
+                                                                   ~~~~~~~~~~~~

Can someone please help me the solve this.

Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206
  • Looks like it might be an encoding issue - what happens if you copy paste the code into notepad and save it as a new script with Encoding "ANSI" or "Unicode"? – Mathias R. Jessen Jan 18 '19 at 15:46
  • I also found [this answer](https://stackoverflow.com/a/12924252/9898643) and [this blog](https://itknowledgeexchange.techtarget.com/powershell/loading-assemblies/). It boils down to that you maybe try `Add-Type` instead of `LoadWithPartialName`. Why then you have no problems with it in PS 4.0 I really can't say.. – Theo Jan 18 '19 at 16:36
  • @MathiasR.Jessen... Thank you.. Saving it with different encoding worked for me.. – Priyanka Pandey Jan 21 '19 at 12:42

1 Answers1

0

To use methods in a namespace you need double quotes after the end of the ]. Ex. [System.Windows.Forms.FormStartPosition]::CenterScreen()

trebleCode
  • 2,134
  • 19
  • 34
  • `[system.windows.forms.formstartposition]::CenterScreen` is an enum value, not a method. See [here](https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.formstartposition?view=netframework-4.7.2) – Theo Jan 18 '19 at 20:11
  • Cheers @Theo, didn't have a windows box around, good info to know though! – trebleCode Jan 18 '19 at 20:58