【问题标题】:PowerShell Script to compare 2 CSV files and return row of results用于比较 2 个 CSV 文件并返回结果行的 PowerShell 脚本
【发布时间】:2019-10-21 14:57:44
【问题描述】:

有 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
}

【问题讨论】:

  • -PassThru 添加到Compare-Object 调用,将输出通过管道传输到Where-Object {$_.SideIndicator -eq '=>'}。 otta 会为您提供第二个集合中与第一个集合不匹配的对象。

标签: powershell compare


【解决方案1】:

第一个问题是因为您在导入时指定了-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
    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多