2015-05-04 85 views
0

我目前正在嘗試PowerShell腳本,該腳本將允許用戶輸入將添加集合然後解析爲XML的服務器列表。我從來沒有試圖在PowerShell中循環,ISE沒有立即窗口,所以我看不到我的數組是否真的在建造。任何人都可以驗證此代碼將起作用嗎?使用循環數組在Powershell中存儲用戶輸入

$Reponse = 'Y' 
$ServerName = $Null 
$ServerList = $Null 
$WriteOutList = $Null 

Do 
{ 
    $ServerName = Read-Host 'Please type a server name you like to minitor. Please use the server FQDN' 
    $Response = Read-Host 'Would you like to add additional servers to this list? (y/n)' 
    $Serverlist = @($ServerName += $ServerName) 
} 
Until ($Response -eq 'n') 
+0

驗證?你爲什麼不試試呢? – Mark

+0

對不起,我的意思是問如何檢查數組是否實際存儲對象? –

回答

0

關於數組不存儲字符串值是因爲語法不正確。要在數組中添加新字符串,請在要插入的字符串後面使用+ =運算符。

  1. 聲明空數組以「$ SERVERLIST = @()」(宣佈不運行在嚴格模式腳本時不需要)
  2. 添加新的字符串數組使用「+ =」操作符
  3. 陣列輸出繼電器使用 「寫輸出」 cmdlet的

由於是

$Reponse = 'Y' 
$ServerName = $Null 
$ServerList = $Null 
$WriteOutList = $Null 

Do 
{ 
    $ServerName = Read-Host 'Please type a server name you like to minitor. Please use the server FQDN' 
    $Response = Read-Host 'Would you like to add additional servers to this list? (y/n)' 
    $Serverlist = @($ServerName += $ServerName) 
} 
Until ($Response -eq 'n') 

$Reponse = 'Y' 
$ServerName = $Null 
$Serverlist = @() 
$WriteOutList = $Null 

Do 
{ 
    $ServerName = Read-Host 'Please type a server name you like to minitor. Please use the server FQDN' 
    $Response = Read-Host 'Would you like to add additional servers to this list? (y/n)' 
    $Serverlist += $ServerName 
} 
Until ($Response -eq 'n') 

Write-Output $Serverlist 

關於你的腳本,我不禁想知道爲什麼你想要用戶輸入? Powershell的重點在於儘可能自動化。我建議使用import-csv cmdlet並參考包含所有服務器名稱的文件。

導入使用進口CSV

$ComputerNames = Import-Csv -Path 'C:\serverlist.csv' -Header 'Computer' 
Write-Output $ComputerNames 

注:將導入使用PSCustomObject,而不是一個數組

CSV文件示例

Server1 
Server2 
Server3 
Server4 

注:只要輸入記事本中的所有服務器以服務器名稱後面的回車結束。

最後從PowershellMagazine檢查這張備忘單。它包含有用的命令,運算符,數組......這幫助我在PowerShell腳本的第一天也分配。

網址:http://download.microsoft.com/download/2/1/2/2122F0B9-0EE6-4E6D-BFD6-F9DCD27C07F9/WS12_QuickRef_Download_Files/PowerShell_LangRef_v3.pdf

相關問題