Reputation: 23
I am trying to write a script using PowerShell to get file size 0kb as mentioned below
$FileExists1 = 'C:\Users\iskandar\Desktop\TEST\*\test0700.txt'
IF (Test-Path $FileExists1) {
If ((Get-Item $FileExists1).length -gt 0kb) {
Write-Output "All file size is good!"
}
Else {
Write-Output " There is a file with 0KB, Please inform support staff"
}
}
if there is multiple folder with multiple file, the script not filter the 0KB file.
for example : lets say I have 30 files and only one file with 0KB, when I run those script, it shows "All file size is good!".
Can anyone advice?. Thank you
Upvotes: 2
Views: 3719
Reputation: 24071
Though Esperento57 has provided a working solution, let's see what is wrong in the original code.
The problem happens as you are hit by object mismatch. Multiple objects have same attributes that contain different things.
For a single file, Get-Item
will return a FileInfo
object that contains file's size in its .Length
attribute.
For multiple files, Get-Item
will return an array of FileInfo
objects. Its .Length
attribute contains the length of the array itself. Thus the statement
If ((Get-Item $FileExists1).length -gt 0kb) {
actually is processed as pseudocode
if ($FileExists1-the-array contains more than 0 elements) {
Upvotes: 0
Reputation: 17462
try this:
$files=gci "C:\Users\iskandar\Desktop\TEST" -file -Recurse | where Length -le 0Kb | select -First 1
if ($files.Count -gt 0)
{
"There is a file with 0KB, Please inform support staff"
}
else
{
"All file size is good!"
}
Upvotes: 3