About | FAQ | Help
Ask Your Question
0

If-condition syntax to check if dir/folder is empty

asked 2018-05-29 07:45:07 -0500

Daizy gravatar image

updated 2018-05-29 07:45:36 -0500

Hello,

I am trying to run a query that if the directory/folder is empty, only then perform certain tasks else exit out.

 $abc_install = "C:\\temp\\abc\\"

        if($abc_install == '') {
            Perform
            following
            tasks
           }
    else {
        exec {'ExitOut':
                    provider => powershell,
                    command     => 'exit 0',
                }
            }

But this line is not working -- if($abc_install == '') { . 'else' statement is directly getting executed.

Can anyone tell me the correct syntax of 'if' statement to check if the folder/dir is empty?

edit retag flag offensive close merge delete

Comments

Besides DaryW correct answer, pls note that you assigned a string to a variable then checked if it's empty. It surely isn't.

Emerson Prado gravatar imageEmerson Prado ( 2018-05-30 08:31:18 -0500 )edit

1 Answer

Sort by ยป oldest newest most voted
1

answered 2018-05-29 11:32:05 -0500

DarylW gravatar image

You can't do logic based on state in the target system while composing your maifest, like you are trying to do above. If you had information from a custom fact or your puppetDB, you could use that information as you are showing above.

However, if what you really want to do is to use an exec, you would have to use the exec resource's unless or onlyif parameter. Note that this is NOT available on other resources, and can not be used to conditionally trigger non-exec resources.

Since I have never done anything on the windows space, I did a little Stack Overflow digging for the powershell syntax needed. I believe you would need an onlyif => '(Get-ChildItem c:\temp\ -force | Select-Object -First 1 | Measure-Object).Count -eq 0' or an unless => '(Get-ChildItem c:\temp\ -force | Select-Object -First 1 | Measure-Object).Count -eq 0'to check if the folder is empty. (found via https://stackoverflow.com/a/27602507)

Overall, I think you would need to do something like the following...

exec {'My First Step, to run when directory is empty':
  command  => $desired_powershell_command_for_first_step,
  provider => 'powershell',
  onlyif   => '(Get-ChildItem c:\temp\ -force | Select-Object -First 1 | Measure-Object).Count -eq 0',
}

or

exec {'My First Step, to run when directory is not empty':
  command  => $desired_powershell_command_for_first_step,
  provider => 'powershell',
  unless   => '(Get-ChildItem c:\temp\ -force | Select-Object -First 1 | Measure-Object).Count -eq 0',
}
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2018-05-29 07:45:07 -0500

Seen: 29 times

Last updated: May 29