Dynamic Parameter cannot be specified in parameter set '__AllParameterSets' - powershell

Hello, I am trying to create a dynamic ValidateSet that is based on the contents of a simple text file for one of my cmdlet parameters. I followed this blog post https://blogs.technet.microsoft.com/pstips/2014/06/09/dynamic-validateset-in-a-dynamic-parameter/, and I came up with the following:
function Remove-NetScalerWhiteListItem
{
[CmdletBinding()]
Param
(
)
DynamicParam
{
$ParameterName = "ServiceGroup"
$AttributeCollection = New-Object System.Collections.ObjectModel.Collection[System.Attribute]
$ParameterAttribute = New-Object System.Management.Automation.ParameterAttribute
$ParameterAttribute.Mandatory = $true
$ParameterAttribute.Position = 0
$ParameterAttribute.DontShow = $false
$serviceGroups = Get-NetScalerWhiteList
$ValidateSetAtrribute = New-Object System.Management.Automation.ValidateSetAttribute($serviceGroups)
$AttributeCollection.Add($ValidateSetAtrribute)
$RunTimeParameter = New-Object System.Management.Automation.RuntimeDefinedParameter($ParameterName, [string], $AttributeCollection)
$RuntimeParameterDictionary = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary
$RuntimeParameterDictionary.Add($ParameterName, $RunTimeParameter)
$RuntimeParameterDictionary
}
Begin
{
$ServiceGroup = $PSBoundParameters[$ParameterName]
}
Process
{
Copy-Item "$masterIgnoreFilePath\ingnore.txt" "$masterIgnoreFilePath\ingnore.bak"
$serviceGroups = Get-NetScalerWhiteList
$serviceGroups.Remove($serviceGroup)
Write-Host $serviceGroups
}
}
This partially works, if I begin by typing Remove-NetScalerWhiteListItem -ServiceGroup my validation set is there and working, however when I select one of the items and run the command I get the following error:
Remove-NetScalerWhiteListItem : Parameter 'ServiceGroup' cannot be specified
in parameter set '__AllParameterSets'.
At line:1 char:1
+ Remove-NetScalerWhiteListItem -servicegroup servicegroupname
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Remove-
NetScalerWhiteListItem], ParameterBindingException
+ FullyQualifiedErrorId : ParameterNotInParameterSet,Remove-
NetScalerWhiteListItem
As for the line $serviceGroups = Get-NetScalerWhiteList that is just a wrapper around a Get-Content call to a specific file.

I think you need one more line. You never add the $ParameterAttribute to the $AttributeCollection. You can do so by using this line $AttributeCollection.Add($ParameterAttribute).
function Remove-NetScalerWhiteListItem
{
[CmdletBinding()]
Param
(
)
DynamicParam
{
$ParameterName = "ServiceGroup"
$AttributeCollection = New-Object System.Collections.ObjectModel.Collection[System.Attribute]
$ParameterAttribute = New-Object System.Management.Automation.ParameterAttribute
$ParameterAttribute.Mandatory = $true
$ParameterAttribute.Position = 0
$ParameterAttribute.DontShow = $false
$serviceGroups = Get-NetScalerWhiteList
$ValidateSetAtrribute = New-Object System.Management.Automation.ValidateSetAttribute($serviceGroups)
$AttributeCollection.Add($ValidateSetAtrribute)
$AttributeCollection.Add($ParameterAttribute)
$RunTimeParameter = New-Object System.Management.Automation.RuntimeDefinedParameter($ParameterName, [string], $AttributeCollection)
$RuntimeParameterDictionary = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary
$RuntimeParameterDictionary.Add($ParameterName, $RunTimeParameter)
$RuntimeParameterDictionary
}
Begin
{
$ServiceGroup = $PSBoundParameters[$ParameterName]
}
Process
{
Copy-Item "$masterIgnoreFilePath\ingnore.txt" "$masterIgnoreFilePath\ingnore.bak"
$serviceGroups = Get-NetScalerWhiteList
$serviceGroups.Remove($serviceGroup)
Write-Host $serviceGroups
}
}

Related

powershell progressbar in groupbox GUI

I'm working on a script but for some reason my ProgressBar won't appear in my groupbox.
I tried a lot of different things (like making the groupbox trensparent) but nothing really work.
Here is my code 'simplified' with just the problematic parts.
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
[System.Windows.Forms.Application]::EnableVisualStyles()
$Form = New-Object System.Windows.Forms.Form
$Form.ClientSize = ‘345,160’
$Form.Text = " bug progressbar "
$Form.StartPosition = "CenterScreen"
#Functions
Function BDDchoice(){
$BDD = $args[0]
$Label2.Text = "it takes a few seconds"
$ProgressBarcheck = New-Object System.Windows.Forms.ProgressBar
$ProgressBarcheck.Location = New-Object System.Drawing.Point(230,49)
$ProgressBarcheck.Size = New-Object System.Drawing.Size(98, 23)
$ProgressBarcheck.Style = "Marquee"
$ProgressBarcheck.MarqueeAnimationSpeed = 20
$ButtonNEXT1.Hide()
$Form.Controls.Add($ProgressBarcheck);
$job1 ={
sleep 10
$bdd_min = $args[0]
echo $bdd_min
}
Start-Job -ScriptBlock $job1 -ArgumentList $BDD -Name bdd
do { [System.Windows.Forms.Application]::DoEvents() } until ((Get-Job -Name bdd).State -eq "Completed")
Wait-Job -Name bdd
$resultat = Receive-Job -Name bdd -Keep
Get-Job | Remove-Job -Force
$TextBoxBDD.text = $resultat
$ProgressBarcheck.Hide()
$ButtonNEXT1.Visible = $true
$Label2.Text = "BDD:"
}
#variables
$BDDXS = #('SCHEM1','SCHEM2','SCHEM3','SCHEM4')
$BDD1 = 'BDD1'
$BDD2 = 'BDD2'
$BDD3 = 'BDD3'
$BDD4 = 'BDD4'
$BDD = $null
#groupbox
$GroupBoxCREATE = New-Object System.Windows.Forms.GroupBox
$GroupBoxCREATE.Location = New-Object System.Drawing.Point(10,5)
$GroupBoxCREATE.Width = 325
$GroupBoxCREATE.Height = 150
$GroupBoxCREATE.Text = " Create "
#combobox ZONE
$comboBoxTRIG = New-Object System.Windows.Forms.ComboBox
$comboBoxTRIG.Location = New-Object System.Drawing.Point(25, 50)
$comboBoxTRIG.Size = New-Object System.Drawing.Size(200, 200)
foreach($BDDX in $BDDXS)
{
$comboBoxTRIG.Items.add($BDDX)
}
$comboBoxTRIG.Text = "REGION"
$comboBoxTRIG.AutoCompleteMode = "SuggestAppend"
$comboBoxTRIG.AutoCompleteSource = "ListItems"
$comboBoxTRIG.SelectedIndex ="0"
#butons
$ButtonNEXT1 = New-Object System.Windows.Forms.Button
$ButtonNEXT1.Location = New-Object System.Drawing.Point(230,49)
$ButtonNEXT1.Size = New-Object System.Drawing.Size(98, 23)
$ButtonNEXT1.Text = "OK"
$ButtonNEXT1.add_Click({
$zone = $comboBoxTRIG.SelectedItem.ToString()
if ($zone -like "SCHEM1"){
$BDD = $BDD1
}
if ($zone -like "SCHEM2") {
$BDD = $BDD2
}
if ($zone -like "SCHEM3") {
$BDD = $BDD3
}
if ($zone -like "SCHEM4") {
$BDD = $BDD4
}
BDDchoice($BDD)
})
#labels
$Label1 = New-Object System.Windows.Forms.Label
$Label1.Location = New-Object System.Drawing.Point(25,25)
$Label1.Text = "REGION :"
$Label2 = New-Object System.Windows.Forms.Label
$Label2.Location = New-Object System.Drawing.Point(25,80)
$label2.Width = 200
$Label2.Text = "BDD :"
#textbox
$TextBoxBDD = New-Object System.Windows.Forms.TextBox
$TextBoxBDD.Location = New-Object System.Drawing.Point(25,100)
$TextBoxBDD.Width = 200
$TextBoxBDD.ReadOnly = $true
$TextBoxBDD.Text = ""
$TextboxBDD.BackColor = "white"
#list form's butons/lists/combobox
$Form.Controls.AddRange(#($TextBoxBDD))
$Form.controls.AddRange(#($Label1,$Label2))
$Form.controls.AddRange(#($ButtonNEXT1))
$Form.controls.AddRange(#($comboBoxTRIG))
$Form.controls.AddRange(#($GroupBoxCREATE))
$Form.ShowDialog()
i'm interested in any idea.
My coworkers could not find anything but I must admit we are far from expert (i'm still learning and so are they).
$Form.Controls.Add($ProgressBarcheck);
It looks like you're adding Progress Bar to your form, NOT the groupbox. Add progress bar to groupbox then add groupbox to form.
$GroupBoxCREATE.Controls.Add($ProgressBarcheck);
$Form.Controls.Add($GroupBoxCREATE);

WinForm not loading the first time

I am writing a program using PowerShell WinForms.
For example, the "Login" part of the program.
#CREDENTIAL CREATE - LOGIN AND PASSWORD INPUT
############################################
#APP FOUNDATION
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
#Login_Form
$Login_Form = New-Object -TypeName System.Windows.Forms.Form
$Login_Form.ClientSize = (New-Object -TypeName System.Drawing.Size -ArgumentList #([System.Int32]340,[System.Int32]110))
$Login_Form.Text = [System.String]'Login_Form'
$Login_Form.add_Load($Login_Form_Load)
$Login_Form.ResumeLayout($false)
$Login_Form.PerformLayout()
$Login_Form.SuspendLayout()
$Login_Form.FormBorderStyle = "FixedDialog"
#Login_Label_User
$Login_Label_User = (New-Object -TypeName System.Windows.Forms.Label)
$Login_Label_User.Location = (New-Object -TypeName System.Drawing.Point -ArgumentList #([System.Int32]12,[System.Int32]9))
$Login_Label_User.Name = [System.String]'Login_Label_User'
$Login_Label_User.Size = (New-Object -TypeName System.Drawing.Size -ArgumentList #([System.Int32]100,[System.Int32]18))
$Login_Label_User.TabIndex = [System.Int32]3
$Login_Label_User.Text = [System.String]'Login:'
$Login_Label_User.UseCompatibleTextRendering = $true
#Login_TextBox_User
$Login_TextBox_User = (New-Object -TypeName System.Windows.Forms.TextBox)
$Login_TextBox_User.Location = (New-Object -TypeName System.Drawing.Point -ArgumentList #([System.Int32]12,[System.Int32]30))
$Login_TextBox_User.Name = [System.String]'Login_TextBox_User'
$Login_TextBox_User.Size = (New-Object -TypeName System.Drawing.Size -ArgumentList #([System.Int32]224,[System.Int32]21))
$Login_TextBox_User.TabIndex = [System.Int32]0
$Login_TextBox_User.Text = ((Get-ADDomain).name + "\")
$Login_TextBox_User.add_TextChanged($Login_TextBox_User_TextChanged)
#Login_TextBox_Password
$Login_TextBox_Password = (New-Object -TypeName System.Windows.Forms.TextBox)
$Login_TextBox_Password.Location = (New-Object -TypeName System.Drawing.Point -ArgumentList #([System.Int32]12,[System.Int32]74))
$Login_TextBox_Password.Name = [System.String]'Login_TextBox_Password'
$Login_TextBox_Password.Size = (New-Object -TypeName System.Drawing.Size -ArgumentList #([System.Int32]187,[System.Int32]21))
$Login_TextBox_Password.TabIndex = [System.Int32]1
$Login_TextBox_Password.Text = [System.String]''
$Login_TextBox_Password.PasswordChar = '*'
#Login_Button_Enter
$Login_Button_Enter = (New-Object -TypeName System.Windows.Forms.Button)
$Login_Button_Enter.Location = (New-Object -TypeName System.Drawing.Point -ArgumentList #([System.Int32]251,[System.Int32]74))
$Login_Button_Enter.Name = [System.String]'Login_Button_Enter'
$Login_Button_Enter.Size = (New-Object -TypeName System.Drawing.Size -ArgumentList #([System.Int32]75,[System.Int32]21))
$Login_Button_Enter.TabIndex = [System.Int32]2
$Login_Button_Enter.Text = [System.String]'ENTER'
$Login_Button_Enter.UseCompatibleTextRendering = $true
$Login_Button_Enter.UseVisualStyleBackColor = $true
$Login_Button_Enter.add_Click($Login_Button_Enter_Click)
#Login_Button_ShowHide
$Login_Button_ShowHide = (New-Object -TypeName System.Windows.Forms.Button)
$Login_Button_ShowHide.Location = (New-Object -TypeName System.Drawing.Point -ArgumentList #([System.Int32]205,[System.Int32]74))
$Login_Button_ShowHide.Name = [System.String]'Login_Button_ShowHide'
$Login_Button_ShowHide.Size = (New-Object -TypeName System.Drawing.Size -ArgumentList #([System.Int32]32,[System.Int32]21))
$Login_Button_ShowHide.TabIndex = [System.Int32]2
$Login_Button_ShowHide.Text = [System.String]'SHOW'
$Login_Button_ShowHide.UseCompatibleTextRendering = $true
$Login_Button_ShowHide.UseVisualStyleBackColor = $true
$Login_Button_ShowHide.add_Click($Login_Button_ShowHide_Click)
#Login_Label_Password
$Login_Label_Password = (New-Object -TypeName System.Windows.Forms.Label)
$Login_Label_Password.Location = (New-Object -TypeName System.Drawing.Point -ArgumentList #([System.Int32]12,[System.Int32]54))
$Login_Label_Password.Name = [System.String]'Login_Label_Password'
$Login_Label_Password.Size = (New-Object -TypeName System.Drawing.Size -ArgumentList #([System.Int32]100,[System.Int32]17))
$Login_Label_Password.TabIndex = [System.Int32]4
$Login_Label_Password.Text = [System.String]'Password:'
$Login_Label_Password.UseCompatibleTextRendering = $true
$Login_Label_Password.add_Click($Label2_Click)
#Form.Controls
$Login_Form.controls.AddRange(#($Login_Label_Password,$Login_Label_User,$Login_Button_Enter,$Login_Button_ShowHide,$Login_TextBox_Password,$Login_TextBox_User))
#Login_Button_Enter Click logic
$Login_Button_Enter_Click = {
$Script:username = $Login_TextBox_User.Text
$Script:password = $Login_TextBox_Password.Text
$Script:secstr = New-Object -TypeName System.Security.SecureString
$Script:password.ToCharArray() | ForEach-Object {$secstr.AppendChar($_)}
$Script:cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $secstr
$Login_Form.Close()
}
#Login_Button_ShowHide Click logic
$Login_Button_ShowHide_Click = {
if($Script:Login_TextBox_Password.PasswordChar -eq '*') {
$Script:Login_TextBox_Password.PasswordChar = 0
$Login_Button_ShowHide.Text = [System.String]'SHOW'
}
elseif($Login_TextBox_Password.PasswordChar -eq 0) {
$Login_Button_ShowHide.Text = [System.String]'HIDE'
$Script:Login_TextBox_Password.PasswordChar = "*"
}
}
#START APPLICATION
[void]$Login_Form.ShowDialog()
When I run the script for the first time, the window and everything else is shown correctly, but the buttons and logic do not work.
For everything to work fine, I need to run it a second time.
How do I make everything work the first time I start it?
I've tried everything that is possible already. I do not understand what is wrong.
PowerShell is a largely interpreted language - statements are executed in line order.
You therefore need to define the event action scriptblocks before you can assign them to the respective event handlers, otherwise you're just assigning $null to the event handlers, which is why none of your buttons work.
# define the scriptblock that's supposed to handle the event action...
$Login_Button_ShowHide_Click = {
if($Script:Login_TextBox_Password.PasswordChar -eq '*') {
$Script:Login_TextBox_Password.PasswordChar = 0
$Login_Button_ShowHide.Text = [System.String]'SHOW'
}
elseif($Login_TextBox_Password.PasswordChar -eq 0) {
$Login_Button_ShowHide.Text = [System.String]'HIDE'
$Script:Login_TextBox_Password.PasswordChar = "*"
}
}
#Login_Button_ShowHide
$Login_Button_ShowHide = (New-Object -TypeName System.Windows.Forms.Button)
$Login_Button_ShowHide.Location = (New-Object -TypeName System.Drawing.Point -ArgumentList #([System.Int32]205,[System.Int32]74))
$Login_Button_ShowHide.Name = [System.String]'Login_Button_ShowHide'
$Login_Button_ShowHide.Size = (New-Object -TypeName System.Drawing.Size -ArgumentList #([System.Int32]32,[System.Int32]21))
$Login_Button_ShowHide.TabIndex = [System.Int32]2
$Login_Button_ShowHide.Text = [System.String]'SHOW'
$Login_Button_ShowHide.UseCompatibleTextRendering = $true
$Login_Button_ShowHide.UseVisualStyleBackColor = $true
# ... _before_ assigning it to handlethe event
$Login_Button_ShowHide.add_Click($Login_Button_ShowHide_Click)
Repeat for all the scriptblocks assigned as event handlers - either move them all to the top of the script, or, move all the .add_<EventName>() calls to the bottom, just before launching the GUI:
# Rest of script goes here ...
# register all event handlers
$Login_TextBox_User.add_TextChanged($Login_TextBox_User_TextChanged)
$Login_Button_Enter.add_Click($Login_Button_Enter_Click)
$Login_Button_ShowHide.add_Click($Login_Button_ShowHide_Click)
# start app
[void]$Login_Form.ShowDialog()

Compound Dynamic Parameters in Powershell

I am attempting to use two Dynamic Parameters in the same cmdlet. The problem is that I would like the second dynamic parameter to use the first parameter to populate the result set.
For example the syntax for using the command could be something like this -
Get-MSRP -Manufacturer Jeep -Trim Rubicon
'Manufacturer' is a dynamic parameter that looks at a file on the disk to populate values for the user. I would 'Trim' to consume the 'Manufacturer' option that the user chose to create a result set of 'Trim'.
My 'Manufacturer' is working correctly but I believe that the value which the user has chosen isn't available when the code for the DynamicParam I've created for 'Trim', has been ran.
Any help?
function Get-MSRP{
[cmdletbinding()]
param()
DynamicParam{
$Param1 = "Manufacturer",0,{GC c:\temp\manufacturers.txt},$False
$Param2 = "Trim",1,{GC c:\temp\$Manufacturer\Trim.txt},$False
Get-DynamicParameterSet $Param1,$Param2
}
begin{
$Manufacturer = $PSBoundParameters["Manufacturer"]
$Trim = $PSBoundParameters["Trim"]
}
process{
return Invoke-Sqlcmd -Database 'db' -ServerInstance 'server' -Query
"Select MSRP from pricing.MSRP where Manufacturer = '$Manufacturer'
and Trim = '$Trim'"
}
}
function Get-DynamicParameterSet{
param($Params)
$RuntimeParameterDictionary = New-Object
System.Management.Automation.RuntimeDefinedParameterDictionary
if($Params[0].GetType().Name -eq "String" ){
Write-Debug "Single Param to build"
$RuntimeParameterDictionary = BuildSet $Params[0] $Params[1]
$([Scriptblock]$Params[2]) $Params[3] $Params[4] $RuntimeParameterDictionary
}else{
foreach($Param in $Params){
$RuntimeParameterDictionary = BuildSet $Param[0] $Param[1]
$([Scriptblock]$Param[2]) $Param[3] $Param[4]
$RuntimeParameterDictionary
}
}
return $RuntimeParameterDictionary
}
function BuildSet{
param(
$ParameterName,
[int]$Position,
[ScriptBlock]$scriptBlock,
$Mandatory,
$SetNames,
[System.Management.Automation.RuntimeDefinedParameterDictionary]$RuntimeParameterDictionary)
Write-Debug "Setting up $ParameterName"
$AttributeCollection = New-Object System.Collections.ObjectModel.Collection[System.Attribute]
$ParameterAttribute = New-Object System.Management.Automation.ParameterAttribute
$ParameterAttribute.Mandatory = $Mandatory
$ParameterAttribute.Position = $Position
$ParameterAttribute.ParameterSetName = $SetNames
$AttributeCollection.Add($ParameterAttribute)
Write-Debug "Generating result set"
$arrSet = Invoke-Command $scriptBlock
Write-Debug "Generated as $arrSet"
$ValidateSetAttribute = New-Object System.Management.Automation.ValidateSetAttribute($arrSet)
$AttributeCollection.Add($ValidateSetAttribute)
$RuntimeParameter = New-Object System.Management.Automation.RuntimeDefinedParameter($ParameterName, [string], $AttributeCollection)
$RuntimeParameterDictionary.Add($ParameterName, $RuntimeParameter)
return $RuntimeParameterDictionary
}
Minimal & Verifiable
function Get-MSRP{
[cmdletbinding()]
param()
DynamicParam{
$Param1 = "Manufacturer",0,{GC c:\temp\manufacturers.txt},$False
$Param2 = "Trim",1,{gci c:\temp\$Manufacturer},$False
Get-DynamicParameterSet $Param1,$Param2
}
begin{
$Manufacturer = $PSBoundParameters["Manufacturer"]
$Trim = $PSBoundParameters["Trim"]
}
process{
return Invoke-Sqlcmd -Database 'db' -ServerInstance 'server' -Query
"Select MSRP from pricing.MSRP where Manufacturer = '$Manufacturer'
and Trim = '$Trim'"
}
}
function Get-DynamicParameterSet{
param($Params)
$RuntimeParameterDictionary = [System.Management.Automation.RuntimeDefinedParameterDictionary]::new()
foreach($Param in $Params){
$ParameterName = $Param[0]
[int]$Position = $Param[1]
[ScriptBlock]$scriptBlock = $([Scriptblock]$Param[2])
$Mandatory = $Param[3]
$SetNames =$Param[4]
$AttributeCollection = [System.Collections.ObjectModel.Collection[System.Attribute]]::new()
$ParameterAttribute = [System.Management.Automation.ParameterAttribute]::new()
$ParameterAttribute.Mandatory = $Mandatory
$ParameterAttribute.Position = $Position
$ParameterAttribute.ParameterSetName = $SetNames
$AttributeCollection.Add($ParameterAttribute)
$arrSet = Invoke-Command $scriptBlock
$ValidateSetAttribute = New-Object System.Management.Automation.ValidateSetAttribute($arrSet)
$AttributeCollection.Add($ValidateSetAttribute)
$RuntimeParameter = New-Object System.Management.Automation.RuntimeDefinedParameter($ParameterName, [string], $AttributeCollection)
$RuntimeParameterDictionary.Add($ParameterName, $RuntimeParameter)
}
return $RuntimeParameterDictionary
}
After some research, i've found that you cannot have this type of 'Compound dynamic parameter' in powershell where the second dynamic parameter uses a variable output from the users first dynamic parameter. The reason being that the values aren't bound to dynamic parameter until the command is ran.
Another note on Dynamic parameters, the ValueFromPipeline order is not respected when using them!

Retrieve Input from PowerShell TextBox

I am working on a PowerShell application which should take a user id as input from a text box, then search ActiveDirectory and return three fields; however, every time I try to use it I receive the following error:
Get-ADUser : Cannot validate argument on parameter 'Identity'. The argument is null. Provide a valid value for the argument, and then try running the command again.
At C:\Path\cc-lookup-gui.ps1:40 char:21
+ $y = Get-ADUser $script:x -Properties cC
+ ~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Get-ADUser], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.ActiveDirectory.Management.Commands.GetADUser
Here is the code for my GUI and search function:
[System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")|Out-Null
[System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")|Out-Null
$net = New-Object -ComObject Wscript.Network
$form = New-Object System.Windows.Forms.Form
$form.Width = 525
$form.Height = 350
$form.FormBorderStyle = [System.Windows.Forms.FormBorderStyle]::Fixed3D
$form.Text = "CC Lookup"
$form.MaximumSize = New-Object System.Drawing.Size(525,350)
$form.StartPosition = "centerscreen"
$form.KeyPreview = $true
$form.Add_KeyDown({if($_.KeyCode -eq "Enter"){$script:x=$input.Text;Search}})
$form.Add_KeyDown({if($_.KeyCode -eq "Escape"){$form.Close()}})
$input = new-object System.Windows.Forms.TextBox
$input.maxLength = 6
$input.Location = New-Object System.Drawing.Size(200,75)
add-type -assemblyName System.Windows.Forms
$label1 = New-Object System.Windows.Forms.Label
$label1.Location = New-Object System.Drawing.Size(200,25)
$label1.AutoSize = $true
$label1.Text = "Enter User ID:"
$Button1 = new-object System.Windows.Forms.Button
$Button1.Location = New-Object System.Drawing.Size(100,132)
$Button1.Size = New-Object System.Drawing.Size(80,20)
$Button1.Text = "Search"
$Button1.Add_Click({$script:x=$input.Text;Search})
$button2 = New-Object System.Windows.Forms.Button
$button2.Location = New-Object System.Drawing.Size(300,132)
$button2.Text = "Clear"
$button2.Add_Click({Clears})
function Search{
$y = Get-ADUser $script:x -Properties cC
$output = $y.samAccountName + '|' + $y.CN + '|' + $y.cC
Add-Type -AssemblyName System.Windows.Forms
$label = New-Object System.Windows.Forms.Label
$label.Text = $Output
$label.AutoSize = $true
$label.Location = New-Object System.Drawing.Size(200,100)
$form.controls.add($label)
}
function Clears{
$label.Text = $null
$input.Text = $null
}
$form.Controls.Add($label1)
$form.Controls.Add($button2)
$form.Controls.Add($input)
$form.Controls.Add($Button1)
$form.Add_Shown({$Form.Activate()})
$Form.ShowDialog()
$x = $input.Text
I have tried declaring the variable $x globally, directly calling $input.text for the search function, and converting $x into a string, all of which return this same error. I'm running PowerShell version 5.
$Input is a special variable name - see help about_Automatic_Variables - and won't do what you expect when you use it in your {} scriptblock, it will refer to scriptblock input (in this case, nothing), instead of your inputbox.
Try renaming it to something else.

Whitelisting IP using appcmd.exe in powershell?

I am running this script to whitelist IP using appcmd.exe.
import-module WebAdministration
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
$Form = New-Object System.Windows.Forms.Form
$Form.Size = New-Object System.Drawing.Size(600,400)
$type="Allow"
function SaveConfig
{
if($Dropdownbox.text -eq "allow"){
$allowed = "true"
}
else{
$allowed = "false"
}
$outputbox.text = "IP " + $ip.text + " is Whitelisted for the URL " + $url.text + " with subnet mask as " + $mask.text + ". " + "User wants to " + $Dropdownbox.text + " this."
<# $url = "capitaliq/ciqdotnet/clientadmin/clientmgr.html"
$ip = "192.168.1.1" #>
$url.text
Set-Location "C:\Windows\System32\inetsrv"; .\appcmd.exe set config "$url.text" -section:system.webServer/security/ipSecurity /+"[ipAddress='$ip.text',allowed='True',subnetMask='$mask.text']" /commit:apphost
$ip.text
$url.text = ""
$ip.text = ""
$dropdownbox.text = ""
}
function close{
$Form.close()
}
$url_label = New-Object System.Windows.Forms.Label
$url_label.Location = New-Object System.Drawing.Size(40,20)
$url_label.Size = New-Object System.Drawing.Size(280,20)
$url_label.Text = "Please enter the URL"
$Form.Controls.Add($url_label)
$url = New-Object System.Windows.Forms.TextBox
$url.Location = New-Object System.Drawing.Size(40,50)
$url.Size = New-Object System.Drawing.Size(260,60)
$Form.Controls.Add($url)
$ip_label = New-Object System.Windows.Forms.Label
$ip_label.Location = New-Object System.Drawing.Size(40,110)
$ip_label.Size = New-Object System.Drawing.Size(280,20)
$ip_label.Text = "Please enter the IP address"
$Form.Controls.Add($ip_label)
$ip = New-Object System.Windows.Forms.TextBox
$ip.Location = New-Object System.Drawing.Size(40,140)
$ip.Size = New-Object System.Drawing.Size(260,60)
$Form.Controls.Add($ip)
$DropDownBox = New-Object System.Windows.Forms.ComboBox
$DropDownBox.Location = New-Object System.Drawing.Size(40,80)
$DropDownBox.Size = New-Object System.Drawing.Size(180,20)
$DropDownBox.DropDownHeight = 400
$Form.Controls.Add($DropDownBox)
$wksList=#("Allow","Deny")
foreach ($wks in $wksList)
{
$DropDownBox.Items.Add($wks)
}
$mask_label = New-Object System.Windows.Forms.Label
$mask_label.Location = New-Object System.Drawing.Size(40,170)
$mask_label.Size = New-Object System.Drawing.Size(280,20)
$mask_label.Text = "Please enter the Subnet Mask"
$Form.Controls.Add($mask_label)
$mask = New-Object System.Windows.Forms.TextBox
$mask.Location = New-Object System.Drawing.Size(40,200)
$mask.Size = New-Object System.Drawing.Size(260,60)
$mask.Text="255.255.255.0"
$Form.Controls.Add($mask)
$Button = New-Object System.Windows.Forms.Button
$Button.Location = New-Object System.Drawing.Size(40,230)
$Button.Size = New-Object System.Drawing.Size(110,50)
$Button.Text = "Save"
$Button.Add_Click({SaveConfig})
$Form.Controls.Add($Button)
$Button = New-Object System.Windows.Forms.Button
$Button.Location = New-Object System.Drawing.Size(170,230)
$Button.Size = New-Object System.Drawing.Size(110,50)
$Button.Text = "Close"
$Button.Add_Click({Close})
$Form.Controls.Add($Button)
$outputBox = New-Object System.Windows.Forms.TextBox
$outputBox.Location = New-Object System.Drawing.Size(350,50)
$outputBox.Size = New-Object System.Drawing.Size(200,200)
$outputBox.MultiLine = $True
$outputBox.ReadOnly= $True
$Form.Controls.Add($outputBox)
$Form.Add_Shown({$Form.Activate()})
[void] $Form.ShowDialog()
For some reason, this line of the code is not getting executed:
Set-Location "C:\Windows\System32\inetsrv"; .\appcmd.exe set config "$url.text" -section:system.webServer/security/ipSecurity /+" [ipAddress='$ip.text',allowed='True',subnetMask='$mask.text']" /commit:apphost
attached is the image which shows that script is only setting location to desired and nothing else. $url.text and $ip.text before and after this line is not getting executed as well.
It most certainly executes appcmd.exe, you just don't see the output from the Click event since it's running in its own scope.
Your appcmd.exe most likely fails because you attempt to expand $ip.text inside a double-quoted string. The parser will convert the entire $ip object to a string and concatenate the literal string ".text", resulting in the following appcmd.exe argument:
/+" [ipAddress='System.Windows.Forms.TextBox, Text: .text',allowed='True',subnetMask='System.Windows.Forms.TextBox, Text: .text']"
Enclose $ip.Text and $mask.Text in a subexpression ($()) instead:
.\appcmd.exe set config "$($url.Text)" -section:system.webServer/security/ipSecurity /+" [ipAddress='$($ip.Text)',allowed='True',subnetMask='$($mask.Text)']" /commit:apphost