Author Posts

July 15, 2016 at 12:46 pm

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.

  • This topic was modified 2 years, 1 month ago by  Tecina S..

July 15, 2016 at 1:22 pm

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

July 15, 2016 at 1:25 pm

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 ?

July 15, 2016 at 1:46 pm

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