SRel
SRel

Reputation: 423

Conversion from Powershell V5 to Powershell V2

According to my last question Compare two Files I finally managed to get all to work inside my .bat. Thanks again for all your support.

However, as I find out today my supervisor is using Powershell in Version 2 instead of 5.1 than I do. The problem now is that the -Raw paramterer of this code:

$target = Get-Content "C:/pbr_tmp/PBreport/trc/TlsTrace.prn" -Raw 

I changed this to:

$target = [System.IO.File]::ReadAllText("C:/pbr_tmp/PBreport/trc/TlsTrace.prn")

Unfortunately, the results are incorrect and I receive following error:

GetEnumerator : Fehler beim Aufrufen der Methode, da [System.Collections.DictionaryEntry] keine Methode mit dem Namen "GetEnumerator" enthält.

Does anyone know if there is something in the complete code snippet which can cause this?

$data = Import-Csv "C:/trc/ModulID.txt" -Delimiter ";" -Header ID,Term 
$target = [System.IO.File]::ReadAllText("C:/pbr_tmp/PBreport/trc/TlsTrace.prn")
$counts = @{}
foreach ($term in $data.Term) {
  $term = $term + " "
  $index = -1
  $count = 0
  do {
    $index = $target.IndexOf($term, $index + 1)
    if ($index -gt -1) { $count++ } else { break; }
  } while ($true);
  if ($count -gt 0) {$counts[$term] = $count}
 }
 $counts = $counts.GetEnumerator() | sort name
 $counts.GetEnumerator() |ForEach-Object {$_.Key, $_.Value -join '' } |Set-Content C:/pbr_tmp/PBreport/trace_results.txt

For example,

$counts = $counts.GetEnumerator() | sort name

Throws no exception.

Upvotes: 0

Views: 537

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174505

Before jumping to the answer, let me just suggest one actual solution:

Abandon PowerShell 2.0 ASAP!

It's old, it's slow, it doesn't have the nice features you're used to and it doesn't ship with the logging features that actually make PowerShell >5 what we might call a securable runtime.

If the choice of operating environment is not yours to influence, read ahead below


After the loop ends, $counts holds an object of type [hashtable].

But after running this statement:

$counts = $counts.GetEnumerator() | sort name

$counts is no longer a [hashtable] - it's an array of individual key-value entries, as spat out by the enumerator.

So, to solve this, remove the GetEnumerator() call on $counts in the last statement:

$counts = $counts.GetEnumerator() | sort name
$counts.GetEnumerator() |ForEach-Object {$_.Key, $_.Value -join '' } |Set-Content C:/pbr_tmp/PBreport/trace_results.txt

Upvotes: 6

Related Questions