PowerShell – Out-File Cannot Validate Argument on Parameter ‘Encoding’

powershell

I've got an automation script that I'm writing, and within it, I'm logging actions to a text file. I've generated the $logFile name with:

$logFile = "\\server\e$\LogPath\log-$(Get-Date -Format 'yyMMdd-HHmmss').log"

I then write to the log file using this syntax:

"Beginning migrations..." | Out-File -FilePath $logFile

This works fine and I can see the output in the resulting log file. However, once I've set everything up, I enter a foreach loop to do the actual work, and log what's happening, like this:

foreach ($system in $systemList) {
  if ($address = Resolve-DnsName -Name $system) {
    "test" | Out-File FilePath $logFile -Append
    "Hostname $system resolves to $($address.IPAddress -join ',')" | Out-File FilePath $logFile -Append
  }
}

At this point in the script, it starts to complain about the file name string encoding:

Out-File : Cannot validate argument on parameter 'Encoding'. The argument "\\server\e$\LogPath\log-180719-101053.log" does not belong to the set "unknown,string,unicode,bigendianunicode,utf8,utf7,utf32,ascii,default,oem" specified by the
ValidateSet attribute. Supply an argument that is in the set and then try the command again.
At C:\users\username\SharePoint\Site\Path\script.ps1:133 char:32
+     "test" | Out-File FilePath $logFile -Append
+                                ~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [Out-File], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.OutFileCommand**strong text**

Can anyone tell me what I'm doing wrong and how to fix this?

Best Answer

You are missing - before FilePath, thus FilePath as string get bound to the first positional parameter, while $logfile get bound to second positional parameter, which is Encoding.