我有一个带有WPF GUI的PowerShell脚本,允许用户输入值并从下拉列表中进行选择。它工作得很好,但有些用户希望绕过它并手动运行脚本(直接在脚本中输入自己的值)。
现在的结构是:
#A bunch of XML and PowerShell that generates the GUI
$WPFbutton.Add_Click({
#Variables that get populated by the GUI
#The rest of the script
})
我想添加类似的内容:
$UseGUI = $true
在脚本的顶部,它们可以更改为false,这将导致脚本忽略XML和按钮单击行。
我以为我可以在基于$UseGUI
的if语句中包含XML内容,但这对按钮点击部分没有帮助。
我知道的一件事是将整个脚本复制并粘贴到基于$UseGUI
的另一个if语句。问题在于它会使脚本大小加倍,并且已经有2000行。
答案 0 :(得分:1)
一个想法是使用函数和参数来识别使用脚本的人是想要使用GUI还是自己提供了正确的信息:
param
(
[Parameter(ParameterSetName = 'Interface',
Mandatory = $true,
Position = 0)]
[switch]
$UseGUI,
[Parameter(ParameterSetName = 'CommandLine',
Mandatory = $true,
Position = 0)]
[ValidateNotNullOrEmpty()]
[string]
$Person
)
function SayHelloTo ($User)
{
Write-Output "Hello $User"
}
if ($UseGUI)
{
#A bunch of XML and PowerShell that generates the GUI
$WPFbutton.Add_Click({
#Variables that get populated by the GUI
#The rest of the script
$variable = "jdope"
SayHello -User $variable
})
}
else
{
SayHello -User $Person
}
参数集将阻止使用这两个选项调用脚本,因此当您检查UseGUI
是否为$True
时,您将知道显示GUI(并获取调用该函数的输入)或用输入调用函数。
要使用GUI,请使用-UseGUI
.\MyPowerShellWpfScript -UseGUI
提供Person
信息并绕过GUI使用
.\MyPowerShellWpfScript -Person "jdope"