我有一個CSV文件,其中包含子網信息,我將用它來填充其中包含服務器信息的CSV文件。我開始通過導入子網信息,並在處理它時,我試圖將多個成員添加到初始哈希表,但它不像預期的那樣工作。 以下代碼按預期處理第一個項目,並使用正確信息創建一個新列。該代碼表明它至少處理了兩個以上的部分,但不添加成員。如何更改代碼以允許將多個成員創建爲單個數組?目標是讓每個子網的網關字段(列)對該子網唯一。將多個成員添加到powershell散列表
五個變量(變量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,,,,
CODE:
$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
出的GridView OUTPUT:
控制檯輸出:
有可能是複製和粘貼錯誤。當滿足$ variableE和$ variableB的條件時,添加「WorkstationGW1」屬性。 – cezarypiatek
@cezarypiatek是的,我在代碼中進行了更改。謝謝! – McKenning
mklement0打敗了我,但你爲什麼要爲你的對象唯一命名的屬性?最佳做法是定義您的基礎對象類和成員變量,並使其保持靜態。 – dontlooknow