PowerShell脚本比较2个CSV文件并返回结果行

时间:2019-10-21 14:57:44

标签: powershell compare

具有2个CSV文件,其中包含4列。显示名称,WindowsEmailAddress,部门,标题。我希望脚本告诉我任何区别,包括新用户是否出现在一张纸上或已被删除。它成功地告诉了我一些更改,但无法输出更改的整个行。因此,部门更改了一个用户,我希望它输出显示名称,电子邮件地址,所以我知道更改的人。

使用以下脚本获得最大的成功。但无法正确输出。有什么想法吗?

$newemp = Import-Csv -Path "C:\temp\departmentlist.csv" -Header department | 
          Select-Object "department"

$ps = Import-Csv -Path "C:\temp\departmentlist2.csv" -Header department | 
      Select-Object "department"

#get list of (imported) CSV properties
$props1 = $newemp | gm -MemberType NoteProperty | select -Expand Name | sort
$props2 = $ps | gm -MemberType NoteProperty | select -Expand Name | sort

#first check that properties match 
#omit this step if you know for sure they will be
if (Compare-Object $props1 $props2) {
    throw "Properties are not the same! [$props1] [$props2]"
} else {
 #pass properties list to Compare-Object
    Compare-Object $newemp $ps -Property $props1
}

1 个答案:

答案 0 :(得分:0)

第一个问题是因为您要在导入时指定-header department | select-object "department"。如果您仅运行Import-Csv -Path "C:\temp\departmentlist.csv" -Header department,就会看到问题。

下一个问题是在props1和props2中,您同时gmselect -expand Name都实际上不在您提供的任何列中。如果您要这样做,请将其更改为select -expand "Display Name",并摆脱gm命令。

接下来,您需要遍历CSV文件中的每个项目,因此在其中添加一个foreach-newemp文件夹中的foreach项目,执行以下命令。

我还建议不要使用“ throw”,因为它实际上会引发错误,并且如果太多的话可能很难阅读。如果这是您要引发实际错误的应用程序,那很好,但出于可读性考虑,我建议改用write-host

在下面的脚本中,我假设WindowsEmailAddress是用户的唯一标识符。我敢肯定这不是最好的方法,但是应该可以。

#Import both files
$newemp = Import-Csv -Path "C:\temp\departmentlist.csv" 
$ps = Import-Csv -Path "C:\temp\departmentlist2.csv" 

#Loop through the file
foreach ($emp in $newemp)
{
    #if the unique identifier of email address in the NewEmp folder exists in the PS folder
    if ($emp.WindowsEmailAddress -in $ps.WindowsEmailAddress)
    {
        #find the person in the PS folder and select their properties
        $psemp = $ps | Where-Object {$_.windowsemailaddress -eq $emp.WindowsEmailAddress}

        #If the properties of emp don't match the properties in the PS folder
        if($emp -notmatch $psemp)
        {
            Write-Host "Properties are not the same! [$emp] [$psemp]" -ForegroundColor Red
        }
    }
    else
    {
    Write-host "Employee $emp does not exist in PS file" -ForegroundColor Yellow
    }

}
相关问题