【发布时间】:2023-04-08 00:42:01
【问题描述】:
我有一个包含子网信息的 CSV 文件,我将使用它来填充包含服务器信息的 CSV 文件。我从导入子网信息开始,在处理它时,我试图将多个成员添加到初始哈希表中,但它的行为不符合预期。 以下代码按预期处理第一项,创建一个包含正确信息的新列。该代码表明它至少处理了两个以上的部分,但没有添加成员。如何更改代码以允许为单个数组创建多个成员?目标是让每个子网的网关字段(列)对该子网唯一。
五个变量(变量A-E)的目的是模仿真实代码中发生的事情。真正的代码从哈希表运行比较,但这不是必需的。如果需要,我愿意更改该部分。
CSV file contents:
NetworkName,Subnet,VLANID,Gateway,VLAN
Servers,"192.168.1.0/24","2041","192.168.1.1","ServerVLAN-2041"
Workstations,"192.168.2.0/24","1001","192.168.2.1","WorkstationVLAN-1001"
DMZ,"172.16.0.0/28","340","172.16.0.1","DMZVLAN-340"
Servers,"192.168.3.0/24","2043","192.168.3.1","ServerVLAN-2043"
Workstations,"192.168.4.0/24","1004","192.168.4.1","WorkstationVLAN-1004"
DMZ,,,,
代码:
$csvfile = "C:\temp\testfile.csv"
$hashArray = Import-CSV $csvfile
$variableA = "192.168.1.0"
$variableB = "192.168.2.0"
$variableC = "192.168.3.0"
$variableD = "172.16.0.1"
$variableE = "192.168.5.0"
$hashArray | % {
if ($_.subnet) { $variable = ($_.subnet).split("/")[0] }
Else { $variable = $null }
if ($variable -eq $variableA -and $variable -ne $null)
{
$_ | add-member "ServerGW1" -NotePropertyValue $_.gateway
Write-Host "Added Server gateway 1: "$_.gateway -ForegroundColor Yellow
}
if ($variable -eq $variableC -and $variable -ne $null)
{
$_ | add-member "ServerGW2" -NotePropertyValue $_.gateway
Write-Host "Added Server gateway 2: "$_.gateway -ForegroundColor Yellow
}
if ($variable -eq $variableB -and $variable -ne $null)
{
$_ | add-member "WorkstationGW1" -NotePropertyValue $_.gateway
Write-Host "Added Workstation gateway 1: "$_.gateway -ForegroundColor Yellow
}
if ($variable -eq $variableD -and $variable -ne $null)
{
$_ | add-member "DMZGW1" -NotePropertyValue $_.gateway
Write-Host "Added DMZ gateway 1: "$_.gateway -ForegroundColor Yellow
}
if ($variable -eq $variableE -and $variable -ne $null)
{
$_ | add-member "WorkstationGW2" -NotePropertyValue $_.gateway
Write-Host "Added Workstation gateway 2: "$_.gateway -ForegroundColor Yellow
}
}
$hashArray | Out-GridView
Out-GridView 输出:
控制台输出:
【问题讨论】:
-
可能存在复制粘贴错误。当满足 $variableE 和 $variableB 的条件时,您添加“WorkstationGW1”属性。
-
@cezarypiatek 是的,我在代码中更改了它。谢谢!
-
mklement0 打败了我,但为什么你要为你的对象使用唯一命名的属性呢?最佳做法是定义您的基对象类和成员变量,并让它们保持静态。
标签: powershell csv hashtable