我用script-block启动了一个脚本:
[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
"@
}
所以我将blabla
替换为$test
。
$test="blabla"
$test3=&$HKCURegistrySettings2
$test3
[ScriptBlock]$HKCURegistrySettings3 = [ScriptBlock]::Create($test3)
$HKCURegistrySettings -eq $HKCURegistrySettings3
现在比较我的第一个$HKCURegistrySettings
和我现在的$HKCURegistrySettings3
他们应该是一样的。但是我弄错了。 1.他们为什么不同? 2.我怎样才能使它们相同? 3.变量是在Here-strings创建之后定义的。其他选择?
当创建scriptblock时,它将用于调用函数 最初:
Invoke-HKCURegistrySettingsForAllUsers -RegistrySettings $HKCURegistrySettings
现在
Invoke-HKCURegistrySettingsForAllUsers -RegistrySettings $HKCURegistrySettings3
所以这就是为什么结果应该是一样的。
谢谢,
答案 0 :(得分:1)
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()
真
答案 1 :(得分:0)
您的ScriptBlock可以像参数一样获取参数。例如:
$sb = { param($x) $a = 'hello'; echo "$a $x!"; }
& $sb 'Powershell'
应打印Hello Powershell!