0

I'm trying to make a simple check for a log file if it's empty or not

if (Get-Content path-to-file) {
  do stuff
}

Issue is that the file may contain a white-space only and return true I tried .replace(" ", "") and .trim() still returns true, what can I do?

1
  • try something like the following to make an array of spaces and/or empty strings into an empty array ... @(' ', '', ' ').Where({-not [string]::IsNullOrWhiteSpace($_)}) Commented Nov 15, 2020 at 15:47

3 Answers 3

2

Found a fix if (-not [string]::IsNullOrWhiteSpace($logContent)) { do stuff }

Sign up to request clarification or add additional context in comments.

1 Comment

You may find if(Get-Content path\to\file -TotalCount 1){ ... } to be more efficient
1

Not necessary to read all file with get-content (be carefull to performance if you test a big file), try this :

if ((get-item "c:\temp\test.txt").Length -gt 0)
{
  "File is not empty"
}
else
{
  "File is empty"
}

1 Comment

This however reports files with just whitespace(s) in them as 'not empty', where the OP wants those files to be regarded empty aswell..
0

You can try this:

$log = Get-Content -Path '.\Desktop\Document.txt'

if ((($null -eq $log) -or ($log.Trim().Length -eq 0))) {
    ...
}
else {
    ...
}

The null check must be first as in case the file is empty it would otherwise throw an error. In this situation, if $log is empty, the second check will be skipped automatically.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.