Mateo Neo
Mateo Neo

Reputation: 81

Using the PS command in the variables SaltStack

I have a State, which should give me an output if the folder exists or not. I don't know how to escape the name of the folder Programs files so PS knows what I mean.

{% set label = salt['cmd.run']('powershell.exe "test-path \"$env:SystemDrive\\Program Files (x86)\\Folder\""') %}

{% if label == 'True' %}
  First:
    cmd.run:
      - name: Write-Host "Exist"
      - shell: powershell

{% else %}
  Secondary:
    cmd.run:
      - name: Write-Host " NOT "
      - shell: powershell
{% endif %}

I get NOT each time I try, but the folder exists

Can you tell me how to make this work. And where can I find information on how to escape lines in YAML

Upvotes: 3

Views: 641

Answers (2)

seshadri_c
seshadri_c

Reputation: 7350

I would recommend using the Saltstack file module to check existence of a directory with the directory_exists function.

This allows us to use the requisite system to trigger further states.

Example:

check-dir-exists:
  module.run:
    - name: file.directory_exists
    - path: 'C:\Program Files (x86)\SomeDirectory'

show-dir-exists:
  cmd.run:
    - name: Write-Host "Dir exists"
    - shell: powershell
    - require:
        - module: check-dir-exists

show-dir-not-exist:
  cmd.run:
    - name: Write-Host "Dir not exists"
    - shell: powershell
    - onfail:
        - module: check-dir-exists

Or store the return value True/False in a variable and match condition in if/else statement.

Example:

{% set label = salt['file.directory_exists']('C:\Program Files (x86)\SomeDirectory') %}

{% if label %}
show-dir-exists:
  cmd.run:
    - name: Write-Host "Dir exists"
    - shell: powershell
{% else %}
show-dir-not-exist:
  cmd.run:
    - name: Write-Host "Dir not exists"
    - shell: powershell
{% endif %}

Upvotes: 1

Leon Bouquiet
Leon Bouquiet

Reputation: 4382

The problem most likely isn't in the call to powershell.exe, because this is what I get when I run the following from the cmd.exe command prompt:

C:\>powershell.exe "test-path \"$env:SystemDrive\\Program Files (x86)\\DoesntExist\""
False

C:\>powershell.exe "test-path \"$env:SystemDrive\\Program Files (x86)\\""
True

Upvotes: 1

Related Questions