Question:
I did search for help regarding my subject but did not find something close to what I need, then here is my doubt:
I need to check the size of a file in a specific folder, if it´s greater than 0 bytes, it´s OK to continue the process, else, abort it writing an output message and sending fail code = 1.
I´ve tried the below but no success on writing the message to the log:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
$FileExists1 = "D:\TEST\FILE\test.txt" IF (Test-Path $FileExists1) { If ((Get-Item $FileExists1).length -gt 0kb) { Write-Output [$(Get-Date)]:" FILE IS OK FOR PROCESSING! - RC = $rc" } Else { $rc = 1 Write-Output [$(Get-Date)]:" FILE HAS 0 BYTES AT D:\TEST\FILE\" Write-Output [$(Get-Date)]:" VALIDATION FINISHED - RC = $rc" Exit $rc } } |
Does any of you know what I could do?
Appreciate your help!
Answer:
The code works absolutely fine. However make sure you provide an initial value to your “$rc”.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
PS C:\WINDOWS\system32> $FileExists1 = 'E:\Work\Powershell\scripts\demo\demo.txt' IF (Test-Path $FileExists1) { If ((Get-Item $FileExists1).length -gt 0kb) { Write-Output [$(Get-Date)]:" FILE IS OK FOR PROCESSING! - RC = $rc" } Else { $rc = 1 Write-Output [$(Get-Date)]:" FILE HAS 0 BYTES AT D:\TEST\FILE\" Write-Output [$(Get-Date)]:" VALIDATION FINISHED - RC = $rc" Exit $rc } } [09/02/2016 23:55:15]: FILE HAS 0 BYTES AT D:\TEST\FILE\ [09/02/2016 23:55:15]: VALIDATION FINISHED - RC = 1 |
However, if you run the code again in the same scope, the value of the variable $rc will be 1. So make sure, you re-initialize the value to 0 or something else, so it might not produce a wrong result.