我目前正在尝试使用powershell脚本,该脚本允许用户输入将添加集合然后解析为XML的服务器列表。我从来没有试过在Powershell中循环,ISE没有立即窗口,所以我无法看到我的数组是否真正被构建。任何人都可以验证此代码是否有效?
$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 :(得分:0)
关于数组没有存储字符串值是因为语法不正确。要在数组中添加新字符串,请在要插入的字符串后面使用+ =运算符。
按原样
$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脚本编写的最初几天进行分配。