PowerShell 函数参数语法 [英] PowerShell function parameters syntax

查看:85
本文介绍了PowerShell 函数参数语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么函数之外的 Write-Host 工作不同比函数内部?

Why do the Write-Host outside of the function work different than inside of the function?

似乎参数变量正在以某种方式从我声明的变量中改变......

It seems like somehow the parameters variables are changing from what I declared it to be...

function a([string]$svr, [string]$usr) {
    $x = "$svr\$usr"
    Write-Host $x
}

$svr = 'abc'
$usr = 'def'
$x = "$svr\$usr"
Write-Host $x
a($svr, $usr)

结果……

abc\def

abc def\

推荐答案

不要在 PowerShell 中使用括号和逗号调用函数或 cmdlet(仅在方法调用中这样做)!

Don't call functions or cmdlets in PowerShell with parentheses and commas (only do this in method calls)!

当您调用 a($svr, $usr) 时,您将传递一个包含两个值的数组作为第一个参数的单个值.它相当于像 a -svr $svr,$usr 一样调用它,这意味着 $usr 参数根本没有指定.所以现在 $x 等于数组的字符串表示(用空格连接),后面跟着一个反斜杠,后面什么都没有.

When you call a($svr, $usr) you're passing an array with the two values as the single value of the first parameter. It's equivalent to calling it like a -svr $svr,$usr which means the $usr parameter is not specified at all. So now $x equals the string representation of the array (a join with spaces), followed by a backslash, followed by nothing.

改为这样称呼它:

a $svr $usr
a -svr $svr -usr $usr

这篇关于PowerShell 函数参数语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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