首页 > 解决方案 > 使用 Start-Process 和 ArgumentList 替换 Powershell 变量

问题描述

我有这段获取 FQDN 并将其保存到变量的 powershell 代码......效果很好:

$FQDN=(Get-WmiObject win32_computersystem).DNSHostName.ToLower()+"."+(Get-WmiObject win32_computersystem).Domain

LogWrite "[+] 系统完全限定的主机名已被检测为:$FQDN"

但是,当我去插入 FQDN 变量的字符串时,我无法让它正常工作。我尝试了反引号、双引号和单引号,但没有成功:

Start-Process -Wait $OUTPATH64 -ArgumentList '/s /v"/qn INSTALLDIR=\"C:\Program Files\IBM\WinCollect\" LOG_SOURCE_AUTO_CREATION_ENABLED=TRUE LOG_SOURCE_AUTO_CREATION_PARAMETERS=""Component1.AgentDevice=DeviceWindowsLog&Component1.Action=create&Component1.LogSourceName=REPLACEME&Component1.LogSourceIdentifier=REPLACEME&Component1.Dest.Name=test.domain.com&Component1.Dest.Hostname=test.domain.com&Component1.Dest.Port=514&Component1.Dest.Protocol=TCP&Component1.Log.Security=true&Component1.Log.System=true&Component1.Log.Application=true&Component1.Log.DNS+Server=false&Component1.Log.File+Replication+Service=false&Component1.Log.Directory+Service=false&Component1.RemoteMachinePollInterval=3000&Component1.EventRateTuningProfile=Default+(Endpoint)&Component1.MinLogsToProcessPerPass=100&Component1.MaxLogsToProcessPerPass=150"""'

在您看到“REPLACEME”字符串的地方,我需要将其替换为 $FQDN 变量字符串。每当我使用反引号$FQDN或双引号“$FQDN”甚至单引号“$FQDN”时,我都会得到“$FQDN”的文字字符串,而代码片段实际上并没有进行变量替换。

我在这里想念什么?我什至也尝试过反引号双引号"$FQDN"。我希望将 REPLACEME 字符串替换为实际主机名 + 域(如 hostname.domain.com)或 $FQDN 变量中设置的内容。ArgumentList 引号需要保持不变,因为我只能通过引用 ArgumentList 以 ' 开头并以 """' 结尾的方式来让我的命令正常工作。任何帮助将不胜感激。

标签: powershellvariablesquotes

解决方案


这就是它应该如何使用反引号:

Start-Process -Wait $OUTPATH64 -ArgumentList "/s /v /qn INSTALLDIR=`"C:\Program Files\IBM\WinCollect\`" LOG_SOURCE_AUTO_CREATION_ENABLED=TRUE LOG_SOURCE_AUTO_CREATION_PARAMETERS=`"Component1.AgentDevice=DeviceWindowsLog&Component1.Action=create&Component1.LogSourceName=$FQDN&Component1.LogSourceIdentifier=$FQDN&Component1.Dest.Name=test.domain.com&Component1.Dest.Hostname=test.domain.com&Component1.Dest.Port=514&Component1.Dest.Protocol=TCP&Component1.Log.Security=true&Component1.Log.System=true&Component1.Log.Application=true&Component1.Log.DNS+Server=false&Component1.Log.File+Replication+Service=false&Component1.Log.Directory+Service=false&Component1.RemoteMachinePollInterval=3000&Component1.EventRateTuningProfile=Default+(Endpoint)&Component1.MinLogsToProcessPerPass=100&Component1.MaxLogsToProcessPerPass=150`""

推荐阅读