如何在PowerShell中通过$VarA引用$VarX的值以实现指定输出?
问题解决
通过变量名引用变量值的正确方法
要实现用$VarA存储$VarX的名称并获取$VarX的值,有几种可靠方式:
方法1:使用Get-Variable(推荐,安全可控)
$VarX = "They can swim" $VarA = 'VarX' # 仅存变量名,无需带$前缀 "What do dogs do? $(Get-Variable -Name $VarA -ValueOnly)"
-ValueOnly参数直接返回变量值,无需额外访问.Value属性。
方法2:通过执行上下文展开字符串
如果$VarA本身是带$的变量引用字符串,可直接展开:
$VarX = "They can swim" $VarA = '$VarX' "What do dogs do? $($ExecutionContext.InvokeCommand.ExpandString($VarA))"
方法3:Invoke-Expression(不推荐,存在注入风险)
仅在$VarA来自可信输入时使用:
$VarX = "They can swim" $VarA = '$VarX' "What do dogs do? $(Invoke-Expression $VarA)"
修复AutoHotkey脚本构建函数
你的Build-AutHotkeyScript函数存在参数语法错误、变量引用不当、内容拼接格式问题,修复后代码如下:
Function Build-AutHotkeyScript{ param( [parameter(Position = 1, ValueFromPipeline)] [string]$Code, [parameter(Position = 2)] [ArgumentCompletions("SingleNoenvJson", "AdvancedHeader", "BasicExit", "AdvancedExit")] [Array]$HeaderFooter = "SingleNoenvJson", "BasicExit", [switch]$NoHeaderFooter ) $Source = "C:\Users\..\Documents\PowerShell\Modules\AutoHotkey\Resources\InteractiveAHK.ahk" # 分步构建脚本内容 $scriptParts = @() if (-not $NoHeaderFooter) { # 根据变量名获取对应Header内容 $headerContent = Get-Variable -Name $HeaderFooter[0] -ValueOnly $scriptParts += $headerContent.Trim() } # 添加用户传入的AHK代码 $scriptParts += $Code.Trim() if (-not $NoHeaderFooter) { # 根据变量名获取对应Footer内容 $footerContent = Get-Variable -Name $HeaderFooter[1] -ValueOnly $scriptParts += $footerContent.Trim() } # 用空行分隔各部分,保证脚本格式清晰 $finalScript = $scriptParts -join "`n`n" # 写入文件并执行 Set-Content -LiteralPath $Source -Value $finalScript -Encoding UTF8 . $source } # ---- Headers ---- $SingleNoenvJson = @" #singleinstance, force #NoEnv #Include <Json> "@ $AdvancedHeader = @" #singleinstance, force #Include <XML> #Include <SomeSuperCoolLib> #Include <HackingTheSystem> [Some more line] "@ # ---- Footers ---- $BasicExit = @" ExitApp [Some more lines coming soon] [Some more lines coming soon] "@ $AdvancedExit = @" ExitApp [Some more lines coming soon] [Some more lines coming soon] "@
关键修复点:
- 补全参数定义中缺失的逗号,解决语法错误。
- 用
Get-Variable根据$HeaderFooter中的变量名,获取对应Header/Footer的实际内容,实现变量间接引用。 - 采用数组收集脚本片段,用
-join "nn"添加空行分隔,保证生成的AHK脚本格式符合预期。 - 增加
-Encoding UTF8避免中文乱码,用.Trim()去除Here-String中的多余缩进。
测试验证
执行Interactive-AHK 'MsgBox, % "The current version is " A_AhkVersion'后,生成的InteractiveAHK.ahk内容将完全符合预期:
#singleinstance, force #NoEnv #Include <Json> MsgBox, % "The current version is " A_AhkVersion ExitApp [Some more lines coming soon] [Some more lines coming soon]
内容的提问来源于stack exchange,提问作者Ralf_Reddings
相关产品推荐
相关产品推荐

