Job fails with 'System.OutOfMemoryException'

Issue

A customized job fails with the error message

Exception of type 'System.OutOfMemoryException' was thrown

Cause

This can be caused when a hashtable is passed to the Out-File cmdlet

$hashtable = @{
Key1 = 'value1'
Key2 = 'value2'
}

Out-File -InputObject $hashtable -LiteralPath "C:\TEMP\outfile.txt" -Force -NoClobber -Encoding utf8 -Append
We suspect that there are other possible causes, but couldn't verify this. Please contact our support if you encounter this issue in any other situation.

Solution 1

Install powerJobs Processor v26.0.4.

Solution 2

You can work around this issue by passing a string to the Out-File cmdlet. You can use the below function to convert any hashtable into a multiline string.

function Convert-HashtableToString {
param([Hashtable]$Hashtable)

$out = ""
foreach ($item in $Hashtable.GetEnumerator()) {
$out += "{0} = {1}`r`n" -f $item.Key, $item.Value
}
return $out
}

$hashtable = @{
Key1 = 'value1'
Key2 = 'value2'
}

Out-File -InputObject (Convert-HashtableToString -Hashtable $hashtable) -LiteralPath "C:\TEMP\outfile.txt" -Force -NoClobber -Encoding utf8 -Append