关于数组不存储字符串值是因为语法不正确。要在数组中添加新字符串,请在要插入的字符串之后使用 += 运算符。
- 用“$Serverlist = @()”声明空数组(在严格模式下不运行脚本时不需要声明)
- 使用“+=”运算符将新字符串添加到数组中
- 使用“Write-Output”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 并引用包含所有服务器名称的文件。
使用 Import-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