1

我正在使用 PowerShell 版本 3。我想解决一个奇怪的问题。我编写了一个 PowerShell 脚本,它读取配置 CSV 文件(带有应用程序路径和名称)并创建一个带有应用程序按钮的表单。当我尝试Start-Process FilePath使用变量提交参数时,它就不起作用了。当我回显变量时,一切都是正确的。也许这里有人知道出了什么问题,可以帮助我。我收到一个错误

Argument is NULL or empty in:
+ $btn.add_click({Start-Process -FilePath "$ButtonCommand"})

我试图用另一个stackoverflow线程的解决方案来解决这个问题:

$ButtonCommand = $ButtonCommand.replace("\","\\").replace('"',"")

并尝试提交$ButtonCommand带有和不带有'"'的

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

1 回答 1

0

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

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

有几个关于此的主题,但在 SOTechNet 上有两个值得注意

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

$btn.add_click({Start-Process -FilePath "$global:ButtonCommand"})
于 2015-06-26T11:48:21.813 回答