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 = "Numeric 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)

1 Answer 1

3
  • $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 (this would work even with incidental whitespace around the numbers):

[int[]] ('3927,3988,4073,4151' -split ',')

Output (an array of [int] values):

3927
3988
4073
4151
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.