合并具有相同 objective 的多个 PowerShell 脚本 - 多维条件

Merge multiple PowerShell scripts with the same objective - multi-dimensional conditionals

我在 WDS 部署后使用 PowerShell 配置系统。 目前,我为每个 OS 和用例都有一个脚本,通过 Unattend.xml 文件自动调用。

现在我的问题是,当我想更改一些常规内容时,我必须在每个脚本中进行更改。

所以我想,我应该将它们合并在一起并将模式作为参数传递(例如客户)或从系统中读取它(例如当我想 运行 仅针对一个 os版本或制造商)。

我阅读了很多关于开关的内容 here,但我不确定这是否是这种情况下的最佳做法。

我将启动定义参数的脚本

Param([string]$customer)
$manufacturer = (Get-CimInstance Win32_ComputerSystem).Manufacturer
$os = (Get-CimInstance Win32_OperatingSystem).version

这是我粘贴在一起的部分脚本:

Write-Output "runnig deskupdate..."
    Start-Process "$install\deskupdate\ducmd.exe" -ArgumentList "/WEB /DRV" -NoNewWindow -Wait

Write-Output "installing java..."
    Get-ChildItem $install\programs -Filter "jre-*" | ForEach {Start-Process $_.Fullname -ArgumentList "/s" -NoNewWindow -Wait}

Write-Output "installing 7zip..."
    Get-ChildItem $install\programs -Filter "7z*" | ForEach {Start-Process $_.Fullname -ArgumentList "/S" -NoNewWindow -Wait}
Write-Output "deactivating uac..."  
    New-ItemProperty -Path HKLM:Software\Microsoft\Windows\CurrentVersion\policies\system -Name EnableLUA -PropertyType DWord -Value 0 -Force

现在我想把它分开,这样我就可以简单地

当然,我可以为每个命令使用 if 子句,但我正在寻找一个不错且可维护的解决方案。你会推荐什么?

这是我的第一个问题,请让我知道,我是否表述得足够清楚。 对于拼写和语法错误,我深表歉意,我的母语是德语。

通常的做法是,如果您 If/then 计数大于 5,或者您有很多选择。最好使用switch语句。

好吧,许多人已经注意到当您的代码中有很多选择项时使用切换 if/then 的性能提升。

所以,很多选择,速度,更易读和维护 = switch。

现在,请不要误会我的意思,我见过一些非常复杂的 switch 语句,即使其中包含额外的 if/then。

PowerShell 的 switch statement 非常灵活:

Param([string] $customer)

$manufacturer = (Get-CimInstance Win32_ComputerSystem).Manufacturer

switch (@{ manufacturer = $manufacturer; customer = $customer }) {
  { $_.manufacturer -eq 'Fujitsu' } { 'run deskupdate' }
  { $True }                         { 'install 7zip'   } # unconditional action
  { $_.customer -ne 'shop_A' }      { 'install java'   }
  { $_.customer -eq 'shop_A' }      { 'deactivate UAC' }
}

请注意如何通过 哈希表 (@{ ...; ... }).

传递要作用的两个维度 - 制造商和客户 -

脚本块形式的条件 ({ ... }) 然后可以作为 $_ 访问哈希表并查询其属性;同样,关联的动作脚本块也可以通过 $_ 访问哈希表。

每个匹配条件都是独立评估的,除非关联的脚本块执行 break