首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在scriptblock和here-string中使用变量

在scriptblock和here-string中使用变量
EN

Stack Overflow用户
提问于 2016-10-08 21:26:18
回答 2查看 1.5K关注 0票数 1

我用script -block启动了一个脚本:

代码语言:javascript
复制
[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
    }

所以这就是它必须看起来的样子。

好吧,但我需要一个变量。

代码语言:javascript
复制
$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

代码语言:javascript
复制
$test="blabla"
$test3=&$HKCURegistrySettings2
$test3

[ScriptBlock]$HKCURegistrySettings3 = [ScriptBlock]::Create($test3)

$HKCURegistrySettings -eq $HKCURegistrySettings3

现在通过比较我的第一个$HKCURegistrySettings和我现在的$HKCURegistrySettings3

它们应该是相同的。但我得到了一个错误。1.为什么它们是不同的? 2.如何使它们相同? 3.变量是在Here-string创建之后定义的。其他选择?

当创建scriptblock时,它最初用于调用函数:

代码语言:javascript
复制
Invoke-HKCURegistrySettingsForAllUsers -RegistrySettings $HKCURegistrySettings

而现在

代码语言:javascript
复制
Invoke-HKCURegistrySettingsForAllUsers -RegistrySettings $HKCURegistrySettings3

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

谢谢,

EN

回答 2

Stack Overflow用户

发布于 2016-10-09 02:49:45

HKCURegistrySettings2还扩展了其他变量,所以$test3字符串不再有$UserProfile.SID,它被扩展了。在PS命令提示符下运行"$HKCURegistrySettings""$HKCURegistrySettings3",自己比较内容。

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

代码语言:javascript
复制
$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
"@
}

然后比较修剪后的内容:

代码语言:javascript
复制
"$HKCURegistrySettings".trim() -eq "$HKCURegistrySettings3".trim()

真正的

票数 1
EN

Stack Overflow用户

发布于 2016-10-10 00:42:43

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

代码语言:javascript
复制
$sb = { param($x) $a = 'hello'; echo "$a $x!"; }
& $sb 'Powershell'

应打印Hello Powershell!

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39932919

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档