Powershell比较来自多个来源的对象

时间:2016-10-07 15:27:22

标签: powershell

我正在尝试构建一个脚本来比较多个CSV文件,并在一个主文件中识别增量。我认为我已接近拥有我需要的东西但是,当我尝试在主对象上设置属性的值时,我遇到了一个问题。

我正在提取一个CSV文件(示例),其中包含计算机名称,位置,IP,Active Directory,SCCM,我将与Active Directory(比较)的输出进行比较,并使用相同的信息。我只想更新第一个文件,其中系统位于名为AD的列中的Active Directory中,是或否。

这是我的代码,需要一些修复它的指导:

$Sample = Import-Csv C:\Scripts\Sample_test_v1.csv
$Compare = Import-Csv C:\Scripts\Sample_AD_v1.csv


$Final = @()


foreach ($Samples in $Sample)
{
    $Final = New-Object System.Object
    $Final | Add-Member -type NoteProperty -name "Computer Name" -value $Samples.ComputerName
    $Final | Add-Member -type NoteProperty -name "IP Address" -value $Samples.IP
    $Final | Add-Member -type NoteProperty -name "Location" -value $Samples.Location

    If ($Samples.ComputerName -contains $compare)
    {$Final | Add-Member -type NoteProperty -name "Active Directory" -value "Yes"}
    Else
    {$Final | Add-Member -type NoteProperty -name "Active Directory" -value "Yes"}
}

2 个答案:

答案 0 :(得分:0)

使用contains,您希望首先收集集合。 (为了清晰起见,还更改样品/样品)

$Samples = Import-Csv C:\Scripts\Sample_test_v1.csv
$Compare = Import-Csv C:\Scripts\Sample_AD_v1.csv

$NewSamples = foreach ($Sample in $Samples) {
    If ($Compare.Computername -contains $Sample.ComputerName) {
        $Sample.AD = "Yes" 
    } Else {
        $Sample.AD =  "No" 
    }
    $Sample
 }

 $NewSamples | Export-Csv C:\Scripts\Sample_test_v1.new.csv -notype

答案 1 :(得分:0)

我用以下代码解决了我的问题,现在有效:

$Final = @()

$Samples = Import-Csv C:\Scripts\Sample_test_v1.csv
$Compare = Import-Csv C:\Scripts\Sample_AD_v1.csv

foreach ($Sample in $Samples)
{
    $Sys = New-Object System.Object
    $Sys | Add-Member -type NoteProperty -name "Computer Name" -value $Sample.ComputerName
    $Sys | Add-Member -type NoteProperty -name "IP Address" -value $Sample.IP
    $Sys | Add-Member -type NoteProperty -name "Location" -value $Sample.Location

    If ($compare.computername  -contains $Sample.ComputerName )
    {$Sys | Add-Member -type NoteProperty -name "Active Directory" -value "Yes"}
    Else
    { $Sys | Add-Member -type NoteProperty -name "Active Directory" -value "No" }
    $Final += $Sys
}