简体   繁体   中英

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

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)"
}

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)"
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM