【问题标题】:Compare two Arrays with Objects as Value比较两个以对象为值的数组
【发布时间】:2012-10-24 07:41:56
【问题描述】:

我是 Powershell 的新手,遇到问题需要一些帮助。我创建了一个函数,它返回一个包含有关目录信息的对象:

日期:2012 年 10 月 12 日

电脑:PC1

目录:C:\TEMP

FOLDERSIZE_IN_MB:70

我遍历目录以收集它们的大小信息,并每周一次将其导出为 CSV 文件。

我的问题从这里开始:

我想获取有关目录增长的一些信息。我开始编写一个脚本,导入最旧和最新的 CSV 文件。

$data="C:\LOG\Data"
$data= gci -path $data -filter "*.csv" 
$temp=""
$old,$new=@()

foreach($item in $data){


    If((Get-Date $item.LastWriteTime -format ("ddMMyyyy")) -gt $temp){

       $new+= $item.FullName |Import-CSV -delimiter ";"
    }
    Elseif((Get-Date $item.LastWriteTime -format ("ddMMyyyy")) -lt $temp){
        $old+= $item.FullName |Import-CSV -delimiter ";"
    }

 $temp=(Get-Date $item.LastWriteTime -format ("ddMMyyyy"))
}

如何比较两个数组以找到两者中相等的 dir vlaues 并计算它们的大小?

我不知道如何检查:

如果 OLD 中的 C:\TEMP 和 NEW 中的 C:\TEMP 则调用 (1-(SIZEOLD/SITZENEW))*100。

我会很高兴得到这样的输出:

日期:2012 年 10 月 12 日

电脑:PC1

目录:C:\TEMP

FOLDERSIZE_IN_MB:80,5

GROWTH_SINCE_LAST_SCAN:15%

这是我为解决我的问题所做的,但我看起来并不可靠,我不知道如何将哈希转换回对象以将结果通过管道传输到 csv。

$old=$old|组对象项 $new=$new|组对象项

$result1=compare $new $old -property Name -includeequal -passthru |WHERE {$_.Sideindicator -eq "=="}
$result2=compare $old $new -property Name -includeequal -passthru |WHERE {$_.Sideindicator -eq "=="}

for($i=0;$i -le $result1.count;$i++){

    if($result1[$i].Name -contains $result2[$i].Name){

      $Size2=($result2[$i].Group)| select-object -property FolderSize_in_MB
      $Size1=($result1[$i].Group)| select-object -property FolderSize_in_MB    

          if(([int]$Size1.FolderSize_in_MB) -ne "0"){
              $growth=(1-(([int]$Size2.FolderSize_in_MB)/([int]$Size1.FolderSize_in_MB)))*100
          }
          else{
                $growth="0"
          }
       }
    else{

    }
    if($result1[$i]){

   $result1[$i].Group| ADD-Member NoteProperty Growth ("{0:n2}"-f $growth +"%")


   } 
}

【问题讨论】:

标签: arrays powershell compare


【解决方案1】:

最先进的方法是基于gci | measure-object -sum length。脚本专家只有done it that way

对于自制解决方案,我宁愿将目录名称和大小存储在一个文件中。下次运行时,导入数据并在其内容上创建一个哈希表。使用每个目录的全名作为哈希键和大小作为值。读取当前目录大小并从哈希表中查看旧大小。 (你可以序列化哈希表,我可能会这样做。)

$ht = @{}
$oldDirs = import-csv "lastStatus.log" # Assume: Name,Size

$oldDirs | % {
  $ht.Add($_.Name, $_.Size)
}

$newDirs = gci -path $data -filter "*.csv"

$newDirs | % {
  # If the hashtable contains dir with same name, read the size and print comparison
  if($ht.ContainsKey($_.FullName)) {
    $oldValue = $ht.Item($_.FullName)
    $("{0}, {1}% " -f $_,   (1-($oldValue/$_.Size))*100 ) # Get current size here somehow
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-17
    • 1970-01-01
    相关资源
    最近更新 更多