我正在尝试一个接一个地批量安装一堆 .msi。但是当我运行我的 powershell 脚本时,msiexec/?好像我的论点是错误的。我在这里缺少什么?
$Path = Get-ChildItem -Path *my path goes here* -Recurse -Filter *.MSI
foreach ( $Installer in ( Get-ChildItem -Path $Path.DirectoryName -Filter *.MSI ) ) {
Start-Process -Wait -FilePath C:\windows\system32\msiexec.exe -ArgumentList "/i '$Installer.FullName'"
}
最佳答案
Olaf's answer包含很好的指示,但让我尝试从概念上归纳一下:
您的尝试有两个不相关的问题:
内部可扩展字符串 (
"..."
) 只有简单的变量引用 ($Installer
) 可以用作-是; 表达式 ($Installer.FullName
) 需要$()
,subexpression operator :$($Installer.FullName)
- 参见 this answer有关 PowerShell 中可扩展字符串(字符串插值)的概述。由于您通过
-ArgumentList
将参数作为 单个字符串 传递给msiexec
,因此仅嵌入 double引号,“...”
,是受支持的,而不是'...'
(单引号)。
因此,使用以下内容(为简洁起见,-FilePath
和 -ArgumentList
参数被按位置传递给 Start-Process
):
Get-ChildItem $Path.DirectoryName -Recurse -Filter *.MSI | ForEach-Object {
Start-Process -Wait C:\windows\system32\msiexec.exe "/i `"$($_.FullName)`""
}
注意:
-ArgumentList
参数是数组类型的([string[]]
)。理想情况下,您因此单独传递参数,作为数组的元素:'/i', $_.FullName
,这不需要您思考关于嵌入 单个 字符串中的引号。
不幸的是,Start-Process
doesn't handle such individually passed arguments properly if they contain embedded spaces , 所以稳健的解决方案是使用单个 -ArgumentList
参数包含所有 参数, 嵌入双引号,根据需要,如上所示。
参见 this answer进行更详细的讨论。
关于powershell - 自动安装 .msi,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63308697/