If clause... HELP

Welcome Forums General PowerShell Q&A If clause... HELP

This topic contains 3 replies, has 3 voices, and was last updated by

 
Participant
2 years, 4 months ago.

  • Author
    Posts
  • #47046

    Participant
    Points: 0
    Rank: Member

    Hello,

    I'm writing a long function and the first part of it, will need to check if two separate folders exist then it proceeds to the next commands down in the function, else it creates it. Here the folders creation part :

    $secondpath = New-item -Path $pathinsecondserver -name "client_$id" -ItemType Directory
    $firstpath = New-item -Path $pathinfirstserver -name "client_$id" -ItemType Directory

    The newly created folders needs to be captured in variable in order to be used later in the function. How can i enclose them in a if...else clause to achieve my goal?

    Thanks.

  • #47055

    Participant
    Points: 21
    Rank: Member

    if (!(test-path "somedirectory")) { new-item -Name foldername -Path somedirectory }

  • #47057

    Participant
    Points: 0
    Rank: Member

    Hi,

    You have defined the path in your "New-Item" as a variable so you can use a "Test-Path" in your if statement like so:

    if (-not(test-path $pathinfirstserver)) {
        $firstpath = New-item -Path $pathinfirstserver -name "client_$id" -ItemType Directory
    }
    
    if (-not(test-path $pathinsecondserver)) {
        $secondpath = New-item -Path $pathinsecondserver -name "client_$id" -ItemType Directory
    }
    

    >

    So you will check the path and if its "not" there will create the folder otherwise it will continue to the next part of your script.

    Does that help ?

  • #47067

    Participant
    Points: 0
    Rank: Member

    Yes it does!!! thank you Graham Beer and Dan Potter

The topic ‘If clause... HELP’ is closed to new replies.