Leandro de Matos
Leandro de Matos

Reputation: 109

Powershell excluding only files

I have the following error when running a script in powershell in version 5.1

Below my simple script to delete files over 180 days, I've tried some solutions but I haven't found what may be the error. (Below error translated from Portuguese to English)

"Out-File: It is not possible to validate the argument in the 'Encoding' parameter. The" files \ DeleteLogFile_21_01_2020.log "argument does not belong to the set" unknown; string; unicode; bigendianunicode; utf8; utf7; utf32; ascii; default; oem "specified by the ValidateSet attribute. Provide an argument that is in the set and try the command again. On the line: 1 character: 36 + $ Log | Out-File -Append D: \ Program files \ DeleteLogFile_ $ LogDate.log + ~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ CategoryInfo: InvalidData: (:) [Out-File], ParameterBindingValidationException + FullyQualifiedErrorId: ParameterArgumentValidationError, Microsoft .PowerShell.Commands.OutFileCommand "

$logPath = "D:\Program files\NICE Systems\Logs"
$nDays = 10
$startTime = Get-Date
$Extensions = "*.*"
$LogDate = (Get-Date).ToString("dd_MM_yyyy")
$Files = Get-Childitem $LogPath -Include $Extensions -Recurse | Where-Object {$_.LastWriteTime -le (Get-Date).AddDays(-$nDays)}
foreach ($File in $Files) 
{
    if ($NULL -ne $File )
    {
        $Log = "`nData e Hora da Deleção: " + $startTime + ". O arquivo " + $File + " foi deletado do sistema."
        $Log | Out-File -Append D:\Program files\DeleteLogFile_$LogDate.log
        Remove-Item $File.FullName | out-null
    }
}

Upvotes: 1

Views: 88

Answers (2)

CM42
CM42

Reputation: 80

You have no quotes around the path to your log file so it's cutting it off at the first space. You can use double quotes and the variable will still be expanded. Single will not be.

$Log | Out-File -Append "D:\Program files\DeleteLogFile_$LogDate.log"

By default windows will also not allow you to write to the program files folder and this is generally not good practice.

Upvotes: 2

Jesse
Jesse

Reputation: 1425

On your Out-File line, your path has a space in it and is not surrounded with quotation marks. In PowerShell, and most scripting languages for that matter, you have to take into account Positional Parameters. Any space that is not in a string or is not followed by/preceded by a parameter (eg. -FileName C:\FileName.txt), will be assumed to precede a positional parameter.

With that said, it is trying to use "D:\Program" as the path, and "files\DeleteLogFile_$LogDate.log" as the encoding type, which is obviously not valid. To fix this, simply make the path a string by putting it in quotation marks like so:

$Log | Out-File -Append "D:\Program files\DeleteLogFile_$LogDate.log"

Upvotes: 1

Related Questions