Alnedru
Alnedru

Reputation: 2655

Powershell script calls other powershell script with read-host lines

I have multiple powershell scripts, each of them has some read-host lines, so that user can provide some values into the script, for example like a name of a server or true/false in some cases.

Ike to create a powershell script, which will call the other scripts, my question: is there a way so that my main script will fill in those read-host values?

Or what is the best way to handle this then? I would prefer not to change my current existing scripts already.

Upvotes: 0

Views: 451

Answers (1)

Duncan
Duncan

Reputation: 95652

Stop trying to re-invent the wheel. Powershell already has the ability to prompt for missing parameters, so use that to read things like server names. It also has the ability to prompt for confirmation before doing anything dangerous:

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:\>

Put your code into cmdlets and use ShouldProcess and you have full control over when the user is prompted to continue and whether or not they are prompted for missing values.

This also gives you dry-run support for free:

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".

Upvotes: 3

Related Questions