在脚本块和下面的字符串中使用变量
问题描述:
我开始了一个脚本脚本块:在脚本块和下面的字符串中使用变量
[scriptblock]$HKCURegistrySettings = {
Set-RegistryKey -Key 'HKCU\Software\Microsoft\Office\14.0\Common' -Name 'qmenable' -Value 0 -Type DWord -SID $UserProfile.SID
Set-RegistryKey -Key 'HKCU\Software\Microsoft\Office\14.0\Common' -Name 'updatereliabilitydata' -Value 1 -Type DWord -SID $UserProfile.SID
Set-RegistryKey -Key 'HKCU\Software\Microsoft\Windows\CurrentVersion\RunOnce' -Name 'blabla' -Value 1 -Type DWord -SID $UserProfile.SID
}
所以这是它必须寻找。
好的,但我需要一个变量。
$HKCURegistrySettings2 = {
@"
set-RegistryKey -Key 'HKCU\Software\Microsoft\Office\14.0\Common' -Name 'qmenable' -Value 0 -Type DWord -SID $UserProfile.SID
Set-RegistryKey -Key 'HKCU\Software\Microsoft\Office\14.0\Common' -Name 'updatereliabilitydata' -Value 1 -Type DWord -SID $UserProfile.SID
Set-RegistryKey -Key 'HKCU\Software\Microsoft\Windows\CurrentVersion\RunOnce' -Name `'$test`' -Value 1 -Type DWord -SID $UserProfile.SID
"@
}
因此,我用$test
替换blabla
。
$test="blabla"
$test3=&$HKCURegistrySettings2
$test3
[ScriptBlock]$HKCURegistrySettings3 = [ScriptBlock]::Create($test3)
$HKCURegistrySettings -eq $HKCURegistrySettings3
所以,现在通过比较我的第一个$HKCURegistrySettings
和我现在$HKCURegistrySettings3
他们应该是相同的。但我得到一个错误。 1.他们为什么不同? 2.我怎样才能让它们变得完全相同? 3.这些变量是在Here-strings创建后定义的。其他选项?
当脚本块是创建那么就用它来调用一个函数 最初:
Invoke-HKCURegistrySettingsForAllUsers -RegistrySettings $HKCURegistrySettings
现在
Invoke-HKCURegistrySettingsForAllUsers -RegistrySettings $HKCURegistrySettings3
所以这就是为什么结果应该是一样的。
感谢,
答
HKCURegistrySettings2
扩展其他变量太多,所以$test3
串不再有$UserProfile.SID
,它已经扩大。通过在PS命令提示符下运行"$HKCURegistrySettings"
和"$HKCURegistrySettings3"
来自己比较内容。
可以逃避那些不使用`$
代替$
需要扩展变量:
$HKCURegistrySettings2 = {
@"
set-RegistryKey -Key 'HKCU\Software\Microsoft\Office\14.0\Common' -Name 'qmenable' -Value 0 -Type DWord -SID `$UserProfile.SID
Set-RegistryKey -Key 'HKCU\Software\Microsoft\Office\14.0\Common' -Name 'updatereliabilitydata' -Value 1 -Type DWord -SID `$UserProfile.SID
Set-RegistryKey -Key 'HKCU\Software\Microsoft\Windows\CurrentVersion\RunOnce' -Name `'$test`' -Value 1 -Type DWord -SID `$UserProfile.SID
"@
}
,然后比较修剪内容:
"$HKCURegistrySettings".trim() -eq "$HKCURegistrySettings3".trim()
真
答
您的ScriptBlock c一个参数,就像一个函数一样。例如:
$sb = { param($x) $a = 'hello'; echo "$a $x!"; }
& $sb 'Powershell'
应打印Hello Powershell!