我用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
"@
}所以我用$test替换了blabla。
$test="blabla"
$test3=&$HKCURegistrySettings2
$test3
[ScriptBlock]$HKCURegistrySettings3 = [ScriptBlock]::Create($test3)$HKCURegistrySettings -eq $HKCURegistrySettings3
现在通过比较我的第一个$HKCURegistrySettings和我现在的$HKCURegistrySettings3
它们应该是相同的。但我得到了一个错误。1.为什么它们是不同的? 2.如何使它们相同? 3.变量是在Here-string创建之后定义的。其他选择?
当创建scriptblock时,它最初用于调用函数:
Invoke-HKCURegistrySettingsForAllUsers -RegistrySettings $HKCURegistrySettings而现在
Invoke-HKCURegistrySettingsForAllUsers -RegistrySettings $HKCURegistrySettings3这就是为什么结果应该是一样的。
谢谢,
发布于 2016-10-09 02:49:45
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()真正的
发布于 2016-10-10 00:42:43
您的ScriptBlock可以接受参数,就像函数一样。例如:
$sb = { param($x) $a = 'hello'; echo "$a $x!"; }
& $sb 'Powershell'应打印Hello Powershell!
https://stackoverflow.com/questions/39932919
复制相似问题