2014-12-02 117 views
0

我有多個PowerShell腳本,它們每個都有一些讀主機行,以便用戶可以在腳本中提供一些值,例如像服務器的名稱或在某些情況下爲真/假。Powershell腳本使用讀主機線路調用其他PowerShell腳本

艾克創建一個PowerShell腳本,這將調用其他腳本,我的問題:有沒有辦法讓我的主腳本將填寫這些讀主機值?

或者什麼是最好的方式來處理呢? 我不想更改我現有的現有腳本。

+0

**有沒有辦法讓我的主要腳本將在那些讀主機值填寫**這將是可能的,但它?也將是一場噩夢。更改腳本以接受值作爲參數。您可以保留'Read-Host'行,但僅在參數不存在時顯示它們。 – arco444 2014-12-02 10:09:58

+0

我明白了,我也在想這件事,但我希望可能有更好的方法來避免這種情況:/ – Alnedru 2014-12-02 10:49:01

+0

不知道你在找什麼_better_方式。你可以創建環境變量,但你需要在最後清理它們。您還可以在腳本之間將這些數據存儲在文件中,並瞭解相關注意事項。不會將參數作爲變量傳遞更乾淨更好 – Matt 2014-12-02 12:17:56

回答

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