Powershell脚本使用读取主机行调用另一个PowerShell脚本

时间:2014-12-02 09:56:06

标签: powershell

我有多个powershell脚本,每个脚本都有一些读取主机行,因此用户可以在脚本中提供一些值,例如服务器名称或某些情况下的true / false。

要创建一个powershell脚本,它将调用其他脚本,我的问题是:有没有办法让我的主脚本填写那些读取主机值?

那么处理这个问题的最佳方法是什么? 我不想更改现有的现有脚本。

1 个答案:

答案 0 :(得分:3)

停止尝试重新发明轮子。 Powershell已经能够提示缺少参数,因此使用它来读取服务器名称等内容。它还能够在做任何危险之前提示确认:

PS C:\> function Foo-Bar
>> {
>>     [CmdletBinding(SupportsShouldProcess=$true,
>>                   ConfirmImpact='High')]
>>     Param
>>     (
>>         # The target server
>>         [Parameter(Mandatory=$true,
>>                    ValueFromPipeline=$true,
>>                    ValueFromPipelineByPropertyName=$true,
>>                    ValueFromRemainingArguments=$false,
>>                    Position=0)]
>>         [ValidateNotNull()]
>>         [string[]]
>>         $ServerName
>>     )
>>
>>     Process
>>     {
>>         foreach ($srv in $ServerName) {
>>             if ($pscmdlet.ShouldProcess("$srv", "Foo-Bar the server"))
>>             {
>>                 Write-Output "$srv has been Foo'ed"
>>             }
>>         }
>>     }
>> }
>>
PS C:\> Foo-Bar

cmdlet Foo-Bar at command pipeline position 1
Supply values for the following parameters:
ServerName[0]: first
ServerName[1]: second
ServerName[2]: third
ServerName[3]:

Confirm
Are you sure you want to perform this action?
Performing the operation "Foo-Bar the server" on target "first".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): y
first has been Foo'ed

Confirm
Are you sure you want to perform this action?
Performing the operation "Foo-Bar the server" on target "second".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): a
second has been Foo'ed
third has been Foo'ed
PS C:\> Foo-Bar alpha,beta -confirm:$False
alpha has been Foo'ed
beta has been Foo'ed
PS C:\>

将代码放入cmdlet并使用ShouldProcess,您可以完全控制何时提示用户继续以及是否提示他们输入缺失值。

这也为您免费提供干运行支持:

PS C:\> Foo-Bar alpha,beta -WhatIf
What if: Performing the operation "Foo-Bar the server" on target "alpha".
What if: Performing the operation "Foo-Bar the server" on target "beta".