empty var in compare-object | powershell

Viewed 25

im quiet new to powerhsell and I have the following goal: My code is supposed to loop through selected subfolders and compare those. The names of the subfolders are identical in both parent folders, however the path before those selected folders are different: C:\temp\parentF1\BackUp* and C:\temp\parentF2\BackUp*

The problem that I have is that even tho I think my $vars that I use for the comparison should have a value, are NULL and I cant think of why!

$path = "subfolder1","subfolder2","subfolder3"
$excludeF1 = @(C:\temp\parentF1\BackUp\*\subfolder5)
$excludeF2 = @(C:\temp\parentF2\BackUp\*\subfolder5)
$x = 0

while($x -lt $path.Count){
$F1 = Get-ChildItem -Recurse -Path "C:\temp\parentF1\BackUp\$path[$x]" |
      Where-Object {$_.FullName -notlike $excludeF1}
$F2 = Get-ChildItem -Recurse -Path "C:\temp\parentF2\BackUp\$path[$x]" |
      Where-Object {$_.FullName -notlike $excludeF2}
Compare-Object -ref $F1 -dif $F2 |
      Select-Object @{Label="$path[$x]";e={$_.InputObject}},`
      @{n="Fundort";e={if($_.SideIndicator -like "=>") {write-output "BackUp F1"}`
      elseif($_.SideIndicator -like "<="){Write-Output "BackUp F2"}}} | Out-File dif.txt
$x++
}
start .\dif.txt

also the out-file cmdlet doesnt work but that`s a dif topic Thanks for any help in advance

1 Answers

This does not work as you expect:

Get-ChildItem ... -Path "C:\temp\parentF1\BackUp\$path[$x]"
  • When using -Path, PowerShell interprets [...] as part of its own wildcard syntax. Use -LiteralPath to prevent that.
  • Anything more complex than simple variable name ($var) must be enclosed in a subexpression $(...).

Similar issue:

Select-Object @{Label="$path[$x]"; ...
  • This can be solved by simply removing the quotation, as $path already contains strings.

Solution:

$F1 = Get-ChildItem -Recurse -LiteralPath "C:\temp\parentF1\BackUp\$($path[$x])" | ...
$F2 = Get-ChildItem -Recurse -LiteralPath  "C:\temp\parentF2\BackUp\$($path[$x])" | ...

Compare-Object ... |
    Select-Object @{Label=$path[$x]; ...

The above fixes your current code, but your code could be simplified like this to avoid the subexpressions:

foreach($currentPath in $path) {
    $F1 = Get-ChildItem -Recurse -Path "C:\temp\parentF1\BackUp\$currentPath" |
          Where-Object FullName -notlike $excludeF1
    $F2 = Get-ChildItem -Recurse -Path "C:\temp\parentF2\BackUp\$currentPath" |
          Where-Object FullName -notlike $excludeF2

    Compare-Object -ref $F1 -dif $F2 |
          Select-Object @{Label=$currentPath;e={$_.InputObject}},`
          @{n="Fundort";e={if($_.SideIndicator -like "=>") {write-output "BackUp F1"}`
          elseif($_.SideIndicator -like "<="){Write-Output "BackUp F2"}}} | Out-File dif.txt
}
Related