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

问题描述 投票:3回答:1

我正在尝试从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 
winforms powershell active-directory powershell-v2.0 powershell-v3.0
1个回答
3
投票

你的Get-ADComputer filter syntax is broken

将其更改为:

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

你的脚本会起作用。

您所关注的文章已经过时 - 有关于它的错误的讨论,以及2014年关于The Scripting Guys' blog here的最新更新示例

© www.soinside.com 2019 - 2024. All rights reserved.