ebrodje
ebrodje

Reputation: 97

Powershell script to loop through variables multiple times

I have 4 variables and I want a script to execute these variables multiple times my thinking is placing each of the variables in their own file and then loop through the files and have the main script which takes the variables loop it.

I'm wondering if this is smart or if I can do it in a simpler way basically it looks like this

File1
$SFTP_NAME = "PATH_1"
$CUSTOMER_NAME = "Customer_1"
$BACKUP_LOCATION = "Customer_1"
$IP_ADDRESS = 192.168.159.11


File2
$SFTP_NAME = "PATH_2"
$CUSTOMER_NAME = "Customer_2"
$BACKUP_LOCATION = "Customer_2"
$IP_ADDRESS = 192.168.159.12



Main Script
    New-Item -ItemType directory -Path \\ftp\Customers\$SFTP_NAME\$CUSTOMER_NAME
    New-Item -ItemType directory -Path \\ftp\Customers\$SFTP_NAME\$CUSTOMER_NAME\$BACKUP_LOCATION
    New-Item -ItemType directory -Path \\ftp\Customers\$SFTP_NAME\$CUSTOMER_NAME\$IP_ADDRESS

Upvotes: 0

Views: 447

Answers (2)

TobyU
TobyU

Reputation: 3908

Create an array and store your configuration data in it using a custom object. Then loop trough the array and use the data to create your items.

$fileList = @()

$fileList += New-Object psobject -Property @{ "SFTP_NAME"="PATH_1"
            "CUSTOMER_NAME"="Customer_1"
            "BACKUP_LOCATION"="Customer_1"
            "IP_ADDRESS"="192.168.159.11"}

$fileList += New-Object psobject -Property @{ "SFTP_NAME"="PATH_2"
            "CUSTOMER_NAME"="Customer_2"
            "BACKUP_LOCATION"="Customer_2"
            "IP_ADDRESS"="192.168.159.12"}

$fileList | foreach {

    New-Item -ItemType directory -Path "\\ftp\Customers\$($_.SFTP_NAME)\$($_.CUSTOMER_NAME)"
    New-Item -ItemType directory -Path "\\ftp\Customers\$($_.SFTP_NAME)\$($_.CUSTOMER_NAME)\$($_.BACKUP_LOCATION)"
    New-Item -ItemType directory -Path "\\ftp\Customers\$($_.SFTP_NAME)\$($_.CUSTOMER_NAME)\$($_.IP_ADDRESS)"
}

Upvotes: 0

Paweł Dyl
Paweł Dyl

Reputation: 9143

I recommend one CSV file with four columns:

$configurations = @'
SFTP_NAME,CUSTOMER_NAME,BACKUP_LOCATION,IP_ADDRESS
PATH_1,Customer_1,Customer_1,192.168.159.11
PATH_2,Customer_2,Customer_2,192.168.159.12
'@ | ConvertFrom-Csv

#or prepare csv file in Excel and import
#$configurations = Import-Csv Csvfile.csv

$configurations | % {
    New-Item -ItemType directory -Path "\\ftp\Customers\$($_.SFTP_NAME)\$($_.CUSTOMER_NAME)"
    New-Item -ItemType directory -Path "\\ftp\Customers\$($_.SFTP_NAME)\$($_.CUSTOMER_NAME)\$($_.BACKUP_LOCATION)"
    New-Item -ItemType directory -Path "\\ftp\Customers\$($_.SFTP_NAME)\$($_.CUSTOMER_NAME)\$($_.IP_ADDRESS)"
}

Upvotes: 2

Related Questions