用可选的调用变量创建一个函数 [英] Create a function with optional call variables
问题描述
有没有一种方法可以在PowerShell函数中创建一个参数,您必须调用它才能考虑它?
一个由commandlet(大胆的是我想要做的):
Invoke-Command
- computername
Server01
-Scriptblock
{...}
下面是我想要用函数做的一个例子
函数DoStuff($ computername,-arg2,-domain $ domain)
测试参数(-domain)if(-domain -eq $ true){
使用$ domain
}
其他{
$ domain =Domain1
}
测试参数($ arg2){
if($ arg2 -eq $ true){
做某事
}
else {
做相反的
}
}
$ b 如果-arg2是现在,我想要一些哈在剧本中。如果-Domain存在并且有它的参数,我希望它被使用,而不是set参数。
解决方案 Powershell为通用参数场景提供了许多内置支持,包括必需参数,可选参数,switch(aka标志)参数和参数集。
默认情况下,所有参数都是可选的。最基本的方法是简单地检查 $ null
中的每一个,然后从那里实现你想要的任何逻辑。这基本上就是您在示例代码中已经显示的内容。
如果您想了解Powershell可为您提供的所有特殊支持,请查看以下链接:
a>
about_Functions_Advanced_Parameters
Is there a way to create a parameter in a PowerShell function where you have to call it in order to have it considered?
An example given by commandlet (the bold being what I want to do):
Invoke-Command
-computername
Server01
-Scriptblock
{...}
Here is an example of what I want to do with the function
Function DoStuff($computername, -arg2, -domain $domain)
Test-parameter(-domain) if (-domain -eq $true) {
use $domain
}
Else {
$domain = "Domain1"
}
test-parameter($arg2) {
if ($arg2 -eq $true) {
Do something
}
else {
Do the opposite
}
}
So in summary:
If "-arg2" is present, I want something to happen in the script. If "-Domain" is present and has an argument with it, I want that to be used rather then the set argument.
解决方案 Powershell provides a lot of built-in support for common parameter scenarios, including mandatory parameters, optional parameters, "switch" (aka flag) parameters, and "parameter sets."
By default, all parameters are optional. The most basic approach is to simply check each one for $null
, then implement whatever logic you want from there. This is basically what you have already shown in your sample code.
If you want to learn about all of the special support that Powershell can give you, check out these links:
about_Functions_Advanced_Parameters
这篇关于用可选的调用变量创建一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!