【问题标题】:Using loop arrays to store user input in Powershell使用循环数组在 Powershell 中存储用户输入
【发布时间】:2015-05-04 22:22:03
【问题描述】:

我目前正在尝试使用 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')

【问题讨论】:

  • 验证?你为什么不试试呢?
  • 对不起,我的意思是问我如何检查may数组是否实际存储对象?

标签: arrays powershell-3.0


【解决方案1】:

关于数组不存储字符串值是因为语法不正确。要在数组中添加新字符串,请在要插入的字符串之后使用 += 运算符。

  1. 用“$Serverlist = @()”声明空数组(在严格模式下不运行脚本时不需要声明)
  2. 使用“+=”运算符将新字符串添加到数组中
  3. 使用“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

【讨论】:

    猜你喜欢
    • 2021-04-04
    • 2013-07-17
    • 1970-01-01
    • 1970-01-01
    • 2011-10-19
    • 2016-10-22
    • 1970-01-01
    • 2017-10-18
    • 1970-01-01
    相关资源
    最近更新 更多