我有多个powershell脚本,每个脚本都有一些read-host行,这样用户就可以在脚本中提供一些值,例如服务器的名称或某些情况下的true/false。
Ike创建一个powershell脚本,它将调用其他脚本,我的问题是:有没有一种方法可以让我的主脚本填充这些读取主机值?
或者,处理这个问题的最好方法是什么?我不想改变我现有的脚本。
发布于 2014-12-02 21:08:18
不要试图重复发明轮子。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".https://stackoverflow.com/questions/27246464
复制相似问题