问题描述
在 bash 中,如果 UserName
未设置,我可以这样做将 name
设置为默认值:
In bash I can do something like this to set name
to a default value if UserName
is not set:
name=${UserName:-James}
Powershell 是否支持这样的功能?
Does Powershell support something like this?
推荐答案
使用函数和参数,我们可以做一些我相信你正在做的事情.
Using functions and parameters we can do something like what I believe you are doing.
函数示例:
function WriteUser
{
param($user = "A User",
$message = "Message")
Write-Host $user
Write-Host $message
}
不带参数调用函数
WriteUser
会给你输出:
用户
留言
WriteUser -user 我"-消息错误"
WriteUser -user "Me" -message "Error"
会写以下内容:
我
错误
一些额外的注意事项,您不必使用参数名称.
A couple extra notes, you do not have to use the parameter names.
WriteUser "Bob" "All Systems Go" would work by the order of the parameters.
您也可以切换命名参数的顺序:
You can switch the order of the named parameters as well:
WriteUser -message "Error" -user "user, user"
该函数会将 放入正确的参数中.
and the function will put the to the correct parameter.
否则,我相信您必须做一些事情来近似三元行为,例如:
Otherwise, I believe you would have to do something to approximate ternary behavior like:
function Like-Tern
{
for ($i = 1; $i -lt $args.Count; $i++)
{
if ($args[$i] -eq ":")
{
$coord = $i
break
}
}
if ($coord -eq 0) { throw new System.Exception "No operator!" }
$toReturn
if ($args[$coord - 1] -eq "")
{
$toReturn = $args[$coord + 1]
}
else
{
$toReturn = $args[$coord -1]
}
return $toReturn
}
此创意的功劳函数文件还可以包括:
Set-Alias ~ Like-Tern -Option AllScope
然后你会像这样使用它:
And then you would use it like:
$var = ~ $Value : "Johnny"
当然,~
完全是随意的,因为我无法让 ${
工作......
Of course, ~
was completely arbitrary because I couldn't get ${
to work...
这篇关于在 Powershell 中为变量设置默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!