PowerShell调用msiexec时变量$domain无法正确传递MyDomain参数的问题求助
Let's break down why your attempts weren't working and how to resolve the variable expansion issue:
Why Your Existing Code Failed
- 写法1 Issue: You wrapped the entire argument string in single quotes (
'...'). PowerShell does not expand variables inside single-quoted strings—so$domainwas passed as a literal string instead of its actual value. - 写法2 Issue: The syntax for the
MyDomainargument was broken. Mismatched quotes ('MyDomain='$domain'') caused a parsing error, and even if it compiled, it wouldn't properly quote the domain value for msiexec.
Correct Solutions
Option 1: Use Double-Quoted String with Escaped Inner Quotes
If you prefer passing a single argument string, use double quotes (to enable variable expansion) and escape inner double quotes with backticks (`):
$domain = '999-Test' Start-Process -FilePath "$env:systemroot\system32\msiexec.exe" ` -ArgumentList "/i `".\agent.msi`" MyServer=`"servername:8080|4344`" MyDomain=`"$domain`"" ` -Wait
The backticks tell PowerShell to treat inner double quotes as literal parts of the argument, not as string delimiters.
Option 2: Split Arguments into an Array (Recommended)
Splitting each msiexec parameter into a separate element in the ArgumentList array avoids quote escaping headaches and is more robust for complex arguments:
$domain = '999-Test' Start-Process -FilePath "$env:systemroot\system32\msiexec.exe" ` -ArgumentList @( '/i', ".\agent.msi", 'MyServer="servername:8080|4344"', "MyDomain=`"$domain`"" ) ` -Wait
Each element is treated as a distinct argument by Start-Process. The MyDomain element uses double quotes to expand $domain, with backticks escaping the inner quotes around the domain value.
Alternative Clean Syntax for the Domain Parameter
For better readability, construct the MyDomain parameter separately:
$domain = '999-Test' $myDomainArg = "MyDomain=`"$domain`"" Start-Process -FilePath "$env:systemroot\system32\msiexec.exe" ` -ArgumentList '/i', '.\agent.msi', 'MyServer="servername:8080|4344"', $myDomainArg ` -Wait
This makes it easier to debug and modify the domain parameter independently.
Verification
After running any of these solutions, check your MSI log to confirm MyDomain is set to the value of $domain (e.g., 999-Test) instead of the literal string $domain.
内容的提问来源于stack exchange,提问作者Xiffus

