【发布时间】:2026-01-28 05:25:02
【问题描述】:
我正在制作一个脚本来安装几个程序。
安装.ps1
$here = Split-Path -Parent $MyInvocation.MyCommand.Path
. "$here\includes\script1.ps1"
. "$here\includes\script2.ps1"
Write-Host "Installing program 1"
Install-ProgramOne
Write-Host "Installing program 2"
Install-ProgramTwo
script1.ps1
param (
[string] $getCommand = "msiexec /a program1.msi /q"
)
function Get-Command {
$getCommand
}
function Install-ProgramOne {
iex $(Get-Command)
}
script2.ps1
param (
[string] $getCommand = "msiexec /a program2.msi /q"
)
function Get-Command {
$getCommand
}
function Install-ProgramTwo {
iex $(Get-Command)
}
当包含两个文件时,$getCommand 变量将被覆盖。
C# 中有命名空间,Ruby 中有模块,但我不知道如何在 Powershell 中保持命名空间分开。
【问题讨论】:
-
您想要这样做有什么特别的原因吗?即使有了基思的修复,我也看不到增加复杂性的好处。一个包含要启动的命令数组和调用数组中每个命令的 foreach 循环的脚本可以用更少的代码完成此操作。
-
这不是*.com/questions/5586692/…的骗子吗?
-
@CitizenRon 我使用 Pester 测试了我的脚本。它们最终具有几乎相同的结构,所以我想遵循 DRY。
标签: powershell