2

I've written a little script that checks for differences between 2 text files.

    $new = get-content $outPutFile
    $old = get-content $outPutFileYesterday
    $result = $null
    $result = Compare-Object $old $new

    $resultHTML =  $result.GetEnumerator() | ConvertTo-Html
    Send-MailMessage -SmtpServer 10.14.23.4 -From me@mail.com -To $toAddress -Subject "DiffTest" -Body "$resultHTML" -BodyAsHtml

When I run it from an active PowerShell prompt, all is well. However, when I try to schedule it to run daily I get this error on the run-time (the block above is in a try catch that mails any execution errors):

Method invocation failed because [System.Management.Automation.PSCustomObject] doesn't contain a method named 'GetEnumerator'.

How can I fix this?

Bart De Vos
  • 571
  • 2
  • 7
  • 23

2 Answers2

2

The script may run in a different user context when scheduled, potentially with a different set of read/write permissions on the filesystem.

However, In PowerShell arrays are automatically enumerated when used in expressions, so you don't need to call the GetEnumerator() method before passing it to ConvertTo-Html.

You could start by changing your script to:

$resultHTML =  $result | ConvertTo-Html

and see how it impacts the result.

Community
  • 1
  • 1
Enrico Campidoglio
  • 56,676
  • 12
  • 126
  • 154
2

Compare-Object either returns:

  • $null: if the ReferenceObject and the DifferenceObject are equal
  • an object of type PSCustomObject: if only one item differs (1)
  • an array of objects: if multiple differences have been found

Of these return values only the last one (the array) has a GetEnumerator() method. ConvertTo-Html produces the expected output when fed either of these return values, so you can safely drop the .GetEnumerator() part (as mentioned by Enrico). Another option is to wrap the $result in an array, which would change line 6 of your script to:

$resultHTML = @($result).GetEnumerator() | ConvertTo-Html

(1) This is the return value for compare-object in your script

jon Z
  • 15,838
  • 1
  • 33
  • 35