Using a $Variable to Submit -Filepath Argument for Start-Process

时间:2015-06-26 10:15:38

标签: powershell powershell-v3.0 start-process

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()

1 个答案:

答案 0 :(得分:0)

您遇到了范围问题。在该小脚本块$buttoncommand内部未初始化。一种解决方案是在自己的变量中声明脚本块。

$clickEvent = {Start-Process -FilePath "$ButtonCommand"}
$btn.add_click($clickEvent)

关于这一点有几个主题但有两个值得关注here at SOon TechNet

同样,你可以使用全局范围内的变量来解决这个问题。

$btn.add_click({Start-Process -FilePath "$global:ButtonCommand"})