如何通过PowerShell中的功能更改脚本划分的变量?

发布于 2025-01-26 03:40:52 字数 288 浏览 2 评论 0 原文

让脚本

[int] $num01 = 2

function setNo ([int] $num02)
{
    $num01 = $num02;
}

write-host $num01

setNo -num02 4

write-host $num01

setNo -num02 6

write-host $num01

产生输出

2
2
2

如何使其产生输出:

2
4
6

Have the script

[int] $num01 = 2

function setNo ([int] $num02)
{
    $num01 = $num02;
}

write-host $num01

setNo -num02 4

write-host $num01

setNo -num02 6

write-host $num01

It produces an output

2
2
2

How to make it produce output:

2
4
6

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

浅沫记忆 2025-02-02 03:40:52

有几种方法可以改变函数范围之外的变量值,例如:

([ref] $num01).Value = $num02;
  • 使用
$script:num01 = $num02;
  • ​/Powershell/module/microsoft.powershell.utility/set-variable?view=powershell-7.2#:%7e:text=the%20set; rel =“ nofollow noreferrer”> set-variable 带有 -scope脚本参数或 $ executionContext
Set-Variable num01 -Value $num02 -Scope Script
# OR
$ExecutionContext.SessionState.PSVariable.Set('script:num01', $num02)

请注意,请注意,在此中,特定情况,以上是必要的,因为外部变量 $ num01 scalarar ,如果是 non-scalar < /em>,即阵列或哈希表:

$num01 = @(2) # => array of a single element, index 0

function setNo ([int] $num02) {
    $num01[0] = $num02 # => updating index 0 of the array
}

setNo 10; $num01 # => 10

There are several ways of altering the value of a variable outside the function's scope, for example:

([ref] $num01).Value = $num02;
$script:num01 = $num02;
  • Using Set-Variable with the -Scope Script argument or $ExecutionContext:
Set-Variable num01 -Value $num02 -Scope Script
# OR
$ExecutionContext.SessionState.PSVariable.Set('script:num01', $num02)

Note that, in this particular case, one of the above is necessary because the outside variable $num01 is a scalar, it would not be the case if it was a non-scalar, i.e. an array or hash table:

$num01 = @(2) # => array of a single element, index 0

function setNo ([int] $num02) {
    $num01[0] = $num02 # => updating index 0 of the array
}

setNo 10; $num01 # => 10
各自安好 2025-02-02 03:40:52

它是
$ script:num01 = $ num02

正如圣地亚哥·斯帕尔顿(Santiago Squarzon)在评论中所写。

it's
$script:num01 = $num02

as Santiago Squarzon wrote in comments.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文