将输入变量从 PowerShell 表单传递到 cmdlet 参数会导致空白数据

Passing input variable from PowerShell form to cmdlet argument results in blank data

我正在尝试从 PowerShell 表单中获取输入的文本字符串,如 WIN,并查找所有计算机名称的前三个字母为 WIN 的计算机。

为此,我建立了一个 Microsoft Technet example 并且只稍微修改了代码以获取输入的文本字符串并将其保存为变量 $global:x。我将该变量 ($global:x) 传递到输出到文件的最后一行代码中的过滤器,但输出文件为空白。我做了一些谷歌搜索,并将变量从 $x 更改为 $global:x 但这没有用。

文件仍然是空白。我对 TechNet 代码示例的唯一更改是将变量从 $x 更改为 $global:x 并在末尾添加过滤器;过滤器是代码中的最后一行,应该将变量结果通过管道传输到输出文件中。

完整代码如下。

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

$objForm = New-Object System.Windows.Forms.Form 
$objForm.Text = "FindSimiliarComputers"
$objForm.Size = New-Object System.Drawing.Size(300,200) 
$objForm.StartPosition = "CenterScreen"

$objForm.KeyPreview = $True
$objForm.Add_KeyDown({if ($_.KeyCode -eq "Enter") 
    {$global:x=$objTextBox.Text;$objForm.Close()}})
$objForm.Add_KeyDown({if ($_.KeyCode -eq "Escape") 
    {$objForm.Close()}})

$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Size(75,120)
$OKButton.Size = New-Object System.Drawing.Size(75,23)
$OKButton.Text = "OK"
$OKButton.Add_Click({$global:x=$objTextBox.Text;$objForm.Close()})
$objForm.Controls.Add($OKButton)

$CancelButton = New-Object System.Windows.Forms.Button
$CancelButton.Location = New-Object System.Drawing.Size(150,120)
$CancelButton.Size = New-Object System.Drawing.Size(75,23)
$CancelButton.Text = "Cancel"
$CancelButton.Add_Click({$objForm.Close()})
$objForm.Controls.Add($CancelButton)

$objLabel = New-Object System.Windows.Forms.Label
$objLabel.Location = New-Object System.Drawing.Size(10,20) 
$objLabel.Size = New-Object System.Drawing.Size(280,20) 
$objLabel.Text = "Please enter the partial computer name"
$objForm.Controls.Add($objLabel) 

$objTextBox = New-Object System.Windows.Forms.TextBox 
$objTextBox.Location = New-Object System.Drawing.Size(10,40) 
$objTextBox.Size = New-Object System.Drawing.Size(260,20) 
$objForm.Controls.Add($objTextBox) 

$objForm.Topmost = $True

$objForm.Add_Shown({$objForm.Activate()})
[void] $objForm.ShowDialog()

Get-ADComputer -filter {name -like "$global:x*" -and Enabled -eq "true" } | Select -expand Name | out-file C:\Users\Admin1\Desktop\computers.txt 

你的

将其更改为:

Get-ADComputer -filter "name -like '$global:x*' -and Enabled -eq 'true'" | Select -expand Name | out-file C:\Users\Admin1\Desktop\computers.txt 

你的脚本会起作用。

您关注的文章已经过时了 - 有关于它有什么问题的讨论,以及 The Scripting Guys' blog here

上 2014 年的新更新示例