1

Command line $X = 3927,3988,4073,4151 looks great,

PS C:\Users\Administrator> $X
3927
3988
4073
4151

but if I have it read from a form it echoes 3927,3988,4073,4151

Should I be using something other than $XBox.Text?

Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
$Title = "Numberic ID"
$Form = New-Object "System.Windows.Forms.Form"
$Form.Width = 850
$Form.Height = 140
$Form.Text = $Title
$Form.StartPosition = [System.Windows.Forms.FormStartPosition]::CenterScreen

$XLabel = New-Object "System.Windows.Forms.Label";$XLabel.Left = 5;$XLabel.Top = 18;$XLabel.Text = 'My Numbers:'
$XBox = New-Object "System.Windows.Forms.TextBox";$XBox.Left = 105;$XBox.Top = 15;$XBox.width = 700
$DefaultValue = ""
$XBox.Text = $DefaultValue
$Button = New-Object "System.Windows.Forms.Button";$Button.Left = 400;$Button.Top = 45;$Button.Width = 100;$Button.Text = "Accept"
$EventHandler = [System.EventHandler]{
    $XBox.Text
    $Form.Close()
}
$Button.Add_Click($EventHandler)
$Form.Controls.Add($button)
$Form.Controls.Add($XLabel)
$Form.Controls.Add($XBox)
$Ret = $Form.ShowDialog()
$X = @($XBox.Text)
mklement0
  • 382,024
  • 64
  • 607
  • 775
Ed Pollnac
  • 121
  • 1
  • 6

1 Answers1

2
  • $X contains an array of numbers - number literals that are parsed into [int] instances, assembled into an [object[]] array via ,, the array constructor operator.

    PS> $X = 3927,3988,4073,4151; $X.GetType().FullName; $X[0].GetType().FullName
    System.Object[]  # Type of the array; [object[]], in PowerShell terms.
    System.Int32     # Type of the 1st element; [int], in PowerShell terms.
    
  • By contrast, $XBox.Text contains a single string that only happens to look like the source code that defined $X array.

If you want to interpret this string as PowerShell source code in order to get an array of numbers, you could use Invoke-Expression, but that is generally ill-advised for security reasons.

A safer way is to perform a constrained interpretation of the string yourself:

PS> [int[]] ('3927,3988,4073,4151' -split ',')
3927
3988
4073
4151
mklement0
  • 382,024
  • 64
  • 607
  • 775