PowerShell: How to Check if File is Empty


You can use the following basic syntax in PowerShell to check if a file is empty:

if ([String]::IsNullOrWhiteSpace((Get-content c:\users\bobbi\my_data.csv)))
{
echo "File is Empty"
}
else
{
echo "File is Not Empty"
}

This particular example checks if the file named my_data.csv is empty or not.

If the file is empty then File is Empty will be returned.

If the file is not empty then File is Not Empty will be returned.

Note: In this example, we consider a file to be “empty” if it contains no characters or only white space.

The following example shows how to use this syntax in practice.

Example: How to Check if File Contains Specific String in PowerShell

Suppose we have the following CSV file named basketball_data.csv that contains information about the number of points, assists and rebounds for various basketball players:

Suppose that this file is saved in the following location:

  • c:\users\bobbi\basketball_data.csv

Suppose that we would like to check if this file is empty.

We can use the following syntax to do so:

if ([String]::IsNullOrWhiteSpace((Get-content c:\users\bobbi\basketball_data.csv)))
{
echo "File is Empty"
}
else
{
echo "File is Not Empty"
}

The following screenshot shows how to use this syntax in practice:

PowerShell check if file is empty

PowerShell returns File is Not Empty since the file basketball_data.csv is indeed not empty and contains content.

However, suppose we have another filed named soccer_data.txt that is empty:

We can use the following syntax in PowerShell to check if this file is empty:

if ([String]::IsNullOrWhiteSpace((Get-content c:\users\bobbi\soccer_data.txt)))
{
echo "File is Empty"
}
else
{
echo "File is Not Empty"
}

The following screenshot shows how to use this syntax in practice:

PowerShell returns File is Empty since the file soccer_data.txt is indeed empty.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Check if File Contains Specific String
PowerShell: How to Replace Multiple Strings in File
PowerShell: How to Replace Special Characters in String
PowerShell: How to Replace Text in String

Leave a Reply