powershell 使用表单的输出不正确

0kjbasz6  于 2024-01-08  发布在  Shell
关注(0)|答案(1)|浏览(198)

命令行$X = 3927,3988,4073,4151看起来很棒,

  1. PS C:\Users\Administrator> $X
  2. 3927
  3. 3988
  4. 4073
  5. 4151

字符串
但是如果我从一个表单中读取它,它会返回3927,3988,4073,4151
我应该使用$XBox.Text以外的东西吗?

  1. Add-Type -AssemblyName System.Windows.Forms
  2. Add-Type -AssemblyName System.Drawing
  3. $Title = "Numeric ID"
  4. $Form = New-Object "System.Windows.Forms.Form"
  5. $Form.Width = 850
  6. $Form.Height = 140
  7. $Form.Text = $Title
  8. $Form.StartPosition = [System.Windows.Forms.FormStartPosition]::CenterScreen
  9. $XLabel = New-Object "System.Windows.Forms.Label";$XLabel.Left = 5;$XLabel.Top = 18;$XLabel.Text = 'My Numbers:'
  10. $XBox = New-Object "System.Windows.Forms.TextBox";$XBox.Left = 105;$XBox.Top = 15;$XBox.width = 700
  11. $DefaultValue = ""
  12. $XBox.Text = $DefaultValue
  13. $Button = New-Object "System.Windows.Forms.Button";$Button.Left = 400;$Button.Top = 45;$Button.Width = 100;$Button.Text = "Accept"
  14. $EventHandler = [System.EventHandler]{
  15. $XBox.Text
  16. $Form.Close()
  17. }
  18. $Button.Add_Click($EventHandler)
  19. $Form.Controls.Add($button)
  20. $Form.Controls.Add($XLabel)
  21. $Form.Controls.Add($XBox)
  22. $Ret = $Form.ShowDialog()
  23. $X = @($XBox.Text)

cld4siwp

cld4siwp1#

***$X包含一个由 numbers - number字面值组成的 array,这些字面值被解析为[int]示例,并通过,数组构造函数运算符组装成一个[object[]]数组。

  1. PS> $X = 3927,3988,4073,4151; $X.GetType().FullName; $X[0].GetType().FullName
  2. System.Object[] # Type of the array; [object[]], in PowerShell terms.
  3. System.Int32 # Type of the 1st element; [int], in PowerShell terms.

字符串

  • 相比之下,**$XBox.Text包含一个 * 单一字符串 *,只是碰巧 * 看起来像 * 定义$X数组的源代码。

如果你想将这个字符串 * 解释为PowerShell源代码 *,以获得一个数字数组,你可以 * 使用Invoke-Expression,但出于安全原因,通常是ill-advised
更安全的方法是自己对字符串进行约束解释(即使数字周围有空格,这也可以工作):

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


输出([int]值的数组):

  1. 3927
  2. 3988
  3. 4073
  4. 4151

展开查看全部

相关问题