如何使用 Powershell 修改父作用域变量 [英] How to modify parent scope variable using Powershell

查看:51
本文介绍了如何使用 Powershell 修改父作用域变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 powershell 还很陌生,我只是不知道如何修改父作用域中的变量:

I'm fairly new to powershell, and I'm just not getting how to modify a variable in a parent scope:

$val = 0
function foo()
{
    $val = 10
}
foo
write "The number is: $val"

当我运行它时,我得到:

When I run it I get:

The number is: 0

我希望它是 10.但是 powershell 正在创建一个新变量,将其隐藏在父作用域中.

I would like it to be 10. But powershell is creating a new variable that hides the one in the parent scope.

我已经尝试过这些,但没有成功(根据文档):

I've tried these, with no success (as per the documentation):

$script:$val = 10
$global:$val = 10
$script:$val = 10

但可以这么说,这些甚至不能编译".我错过了什么?

But these don't even 'compile' so to speak. What am I missing?

推荐答案

您不需要使用全局作用域.shell 控制台中可能已经存在同名变量,您可以改为更新它.使用脚本范围修饰符.使用范围修饰符时,不要在变量名中包含 $ 符号.

You don't need to use the global scope. A variable with the same name could have been already exist in the shell console and you may update it instead. Use the script scope modifier. When using a scope modifier you don't include the $ sign in the variable name.

$script:val=10

$script:val=10

这篇关于如何使用 Powershell 修改父作用域变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆