1

我用脚本块开始了一个脚本:

[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 之后定义的。其他选择?

创建脚本块后,它用于调用函数最初:

Invoke-HKCURegistrySettingsForAllUsers -RegistrySettings $HKCURegistrySettings

现在

Invoke-HKCURegistrySettingsForAllUsers -RegistrySettings $HKCURegistrySettings3

所以这就是为什么结果应该是一样的。

谢谢,

4

2 回答 2

1

HKCURegistrySettings2也扩展了其他变量,因此$test3string 不再具有$UserProfile.SID,它已被扩展。通过运行"$HKCURegistrySettings""$HKCURegistrySettings3"在 PS 命令提示符中自行比较内容。

`$您可以使用而不是转义那些不需要扩展的变量$

$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-08T18:49:44.603 回答
0

您的 ScriptBlock 可以接受参数,就像函数一样。例如:

$sb = { param($x) $a = 'hello'; echo "$a $x!"; }
& $sb 'Powershell'

应该打印Hello Powershell!

于 2016-10-09T16:42:42.897 回答