我正在尝试从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
答案 0 :(得分: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上的新更新示例