需要获取我的$sw
CSV文件并使用foreach
将其与哈希转换表进行比较$swtranslation
键字段,然后输出匹配项,包括与文本文件匹配的哈希表的值。
我遇到的问题是它会运行搜索几分钟并返回sw_names.txt输出文件,其中没有任何内容。 它应该有超过 1074+ 场比赛。 我的猜测是我的语法或有些不对。
请参阅我到目前为止所做的事情的代码。
# This is the CSV file listing all the network switches I need to run against the translation table.
$sw = Import-Csv .AllDeviceForExport.csv -Header Host_Name, IP_Address
# Compile the switch translation table for processing and convert to hash //
$swtranslation = @{};
Import-Csv .sw_translation.csv -Header Host_Name, DataSpace_ID | % {
$swhash[$_.Host_Name] = $_.DataSpace_ID
}
# Run the Switch listing $sw against the translation table $swtranslation
# matching the DataSpace_ID and merging DataSpace_ID and Host name and
# all other switch fields together in output //
foreach ($key in $swhash.Keys) {
$sw | Select-Object @{n="Name";e={$outputhash[$swhash.Keys($_.Host_Name).Value]}},* |
Where-Object { $_.Name -ne $null } |
Foreach { $_ -replace '--' } |
Out-File ./sw_names.txt -Force
}
预期成果:
Host_Name DataSpace_ID ABC-123-3750-SW1 1 DEF-234-2950-SW1 5 DEF-234-2950-SW2 5 GHI-567-4510-SW1 6 GHI-567-4510-SW2 6
目前还不清楚你在追求什么。
您有两个没有标题的 csv 文件,
.AllDeviceForExport.csv -Header Host_Name, IP_Address
.sw_translation.csv -Header Host_Name, DataSpace_ID
通常,一个从一个文件构建一个哈希表,然后迭代另一个文件以检查是否存在匹配的属性。
你的代码试图做的是构建哈希表,迭代它的键,然后(非常低效地(在每个键上搜索整个另一个文件,挫败整个想法。
不知道应该检查哪些文件Host_Name
属性,我建议采用不同的方法:
使用Compare-Object
## Q:Test2019 815SO_57515952.ps1
# simulate $swtrans = Import-Csv .sw_translation.csv -Header Host_Name, DataSpace_ID
$swtrans = @"
ABC-123-3750-SW1,1
DEF-234-2950-SW1,5
DEF-234-2950-SW2,5
GHI-567-4510-SW1,6
GHI-567-4510-SW2,6
"@ -split 'r?n' | ConvertFrom-Csv -Header Host_Name, DataSpace_ID
# simulate $sw = Import-Csv .AllDeviceForExport.csv -Header Host_Name, IP_Address
$sw = @"
DEF-234-2950-SW1,192.168.234.1
DEF-234-2950-SW2,192.168.234.2
GHI-567-4510-SW1,192.168.567.1
GHI-567-4510-SW2,192.168.567.2
GHI-567-4510-SW3,192.168.567.3
"@ -split 'r?n' | ConvertFrom-Csv -Header Host_Name, IP_Address
Compare-Object -Ref $swtrans -Diff $sw -Property Host_Name -PassThru -IncludeEqual
这会产生:
> Q:Test2019 815SO_57515952.ps1
Host_Name DataSpace_ID SideIndicator
--------- ------------ -------------
DEF-234-2950-SW1 5 ==
DEF-234-2950-SW2 5 ==
GHI-567-4510-SW1 6 ==
GHI-567-4510-SW2 6 ==
GHI-567-4510-SW3 =>
ABC-123-3750-SW1 1 <=
SideIndicator
属性可用于指定要输出和禁止输出的行。