比较Powershell中的历史数据并输出昨天到今天的不同值

时间:2019-10-24 22:09:06

标签: arrays powershell csv datatables compare

我有两个表需要比较今天和昨天的价值之间的差异,并告诉我发生了什么变化。注意:我在图像的两个表中使用了“今天”和“昨天”来代替日期,但是实际的表中都有日期。

我需要一个Powershell脚本,该脚本将使用DeviceName和PowerState并告诉我昨天和今天之间的更改。在示例中,我只需要告诉我从昨天到今天的更改:“设备B已关闭”。然后,我将每天运行该脚本以向团队发送电子邮件。该脚本还应让我知道设备从昨天到今天是否开机。

数据在SQL中,在PowerShell中,我已将数据从SQL中拉出并放入两个单独的CSV中,然后将每个CSV导入了两个单独的数组中。我正在考虑要遍历每个设备名称的ForEach循环,但是我被困在那里。

这是我正在使用的脚本。 (运行查询是我正在加载的模块中的一个函数)。为了保护我们,服务器名称已更改为“ ServerA”。

Import-Module TeamTools -DisableNameChecking

$YD=(Get-date (get-date).AddDays(-1) -Format "MM-dd-yyyy")
$TD=Get-Date -Format "MM-dd-yyyy"

$YData=Run-query -server ServerA -database Inventory -query "SELECT DeviceName,Powerstate FROM DeviceInventoryHistory WHERE SampleDate = '$YD' ORDER BY DeviceName"
$TData=Run-query -server ServerA -database Inventory -query "SELECT DeviceName,Powerstate FROM DeviceInventory WHERE SampleDate = '$TD' ORDER BY DeviceName"

$YData | Export-Csv -Path C:\Temp\YData.csv -NoTypeInformation
$TData | Export-Csv -Path C:\Temp\TData.csv -NoTypeInformation

$a=Import-CSV -Path C:\Temp\TData.csv
$b=Import-CSV -Path C:\Temp\YData.csv

Compare-Object -ReferenceObject ($a | Select-Object -Property 'DeviceName','PowerState') -DifferenceObject ($b | Select-Object -Property 'DeviceName','PowerState')

我也试图从数组中选出条目,但没有得到结果:

Compare-Object -ReferenceObject ($b | Where-Object {$_.DeviceName -eq 'Device B'}) -DifferenceObject ($a | Where-Object {$_.DeviceName -eq 'DeviceB'})

还尝试使用SQL数据(不使用CSV)

Compare-Object -ReferenceObject ($YData | Select-Object -Property 'DeviceName','PowerState' | Where-Object {$_.DeviceName -eq 'Device B'}) -DifferenceObject ($TData | Select-Object -Property 'DeviceName','PowerState' | Where-Object {$_.DeviceName -eq 'Device B'})

这是CSV中的设备B,用于证明两者不同:

PS C:\Windows\system32> $b | Where-Object {$_.DeviceName -eq 'Device B'}

DeviceName      Powerstate   
----------      ----------  
Device B        Powered Off

PS C:\Windows\system32> $a | Where-Object {$_.DeviceName -eq 'Device B'}

DeviceName      Powerstate  
----------      ----------  
Device B        Powered On

See image of the two tables here

First object in arrays a and b

谢谢!

1 个答案:

答案 0 :(得分:0)

老实说,我会用SQL做到这一点。

Select today.DeviceName, today.PowerState from
(SELECT DeviceName,Powerstate FROM DeviceInventoryHistory WHERE SampleDate = '$YD') as yest join (SELECT DeviceName,Powerstate FROM DeviceInventoryHistory WHERE SampleDate = '$TD') as today on yest.DeviceName = today.DeviceName where yest.Powerstate <> today.Powerstate 

您使用今天使用的查询,而昨天使用的唯一查询,将它们加入相同的名称(计算机名称或唯一ID或...),然后在电源状态不同的情况下返回结果。

您最终将获得一列已更改的计算机及其当前状态的列表。如果需要,您还可以返回yest.PowerState,但这与今天没有一样。