I'm using PowerShell Version 3.
I have a weird problem I would like to fix. I've written a PowerShell script which reads a config CSV file (with application paths and names) and creates a form with application buttons. When I try to submit the Start-Process FilePath
argument with a variable it just wont work. When I echo the variable everything is correct. Maybe someone here knows whats wrong and can help me.
I get an error that the
Argument is NULL or empty in:
+ $btn.add_click({Start-Process -FilePath "$ButtonCommand"})
I tried to fix the problem with a solution of another stackoverflow thread:
$ButtonCommand = $ButtonCommand.replace("\","\\").replace('"',"")
and tried to submit the $ButtonCommand
with and without the '"'
#Search Script Path, Locate Config File in same Path
$fullPathIncFileName = $MyInvocation.MyCommand.Definition
$currentScriptName = $MyInvocation.MyCommand.Name
$currentExecutingPath = $fullPathIncFileName.Replace($currentScriptName, "")
$ConfigFile = $currentExecutingPath + "admintools.conf"
#Read Config File
$StringArray = Get-Content $ConfigFile
#Count Lines in Config File
$ConfigLineCount = Get-Content $ConfigFile | Measure-Object –Line
# Create Button Function
function CreateButton ($ButtonCommand, $ButtonName, $ButtonLocX, $ButtonLocY, $ButtonSizeX, $ButtonSizeY)
{
$btn = New-Object System.Windows.Forms.Button
$btn.add_click({Start-Process -FilePath "$ButtonCommand"})
$btn.Text = $ButtonName
$btn.Location = New-Object System.Drawing.Size($ButtonLocX,$ButtonLocY)
$btn.Size = New-Object System.Drawing.Size($ButtonSizeX,$ButtonSizeY)
$btn.Cursor = [System.Windows.Forms.Cursors]::Hand
$btn.BackColor = [System.Drawing.Color]::LightGreen
$form.Controls.Add($btn)
}
# Define Form
Add-Type -AssemblyName System.Windows.Forms
$form = New-Object Windows.Forms.Form
$form.Size = New-Object Drawing.Size @(260,250)
$Form.Text = "Tools"
$form.StartPosition = "CenterScreen"
#For each line in the configfile a button gets created.
foreach ($ArrayLine in $StringArray)
{
$Ar = [string]$ArrayLine
$Ar = $Ar.Split(";")
$UserArray += @($Ar[1])
CreateButton $Ar[0] $Ar[1] $Ar[2] $Ar[3] $Ar[4] $Ar[5]
}
#Show Form
$drc = $form.ShowDialog()
You are running into a scope issue. Inside that small script block
$buttoncommand
is not initialized. One solution would be to declare the script block in its own variable.There are a couple of threads about this but two worth noting here at SO and on TechNet
In that same vein you could use a variable in the global scope to get around this issue.