I have a CSV file that includes custoomers informations, from it I'm able to create folders for each customers using the below script :
$Names = Import-Csv -Path “$PSScriptRoot\Info.csv” | Select-Object customer, info
Set-Location -Path "$PSScriptRoot\Collection"
foreach($customer in $Names) {
$CustomerPath = '{0}{1}' -f $Customer.customer, $Customer.Info
if (Test-Path -Path .\$CustomerPath) {
$Message = '{0}{1} {2} exists' -f "`t", $Customer.Client, $Customer.Info
Write-Message -Message $Message -ForegroundColor Green
}
else { $null = mkdir $CustomerPath
$Message = '{0}{1} {2} created' -f "`t", $Customer.Client, $Customer.Info
Write-Host -Message $Message -ForegroundColor Green
}
}
My issues is that I'm not able to create subdirectories for each customers. in other work I need to create some other folders into each customer folders that will receive files collections, for example CSV files [other data], excel files and so on...
structure should be :
customerFolder | CSV folder ESXCEL Folder DOC Folder
I already tried to modify my script above in order to create sub-directories without success. as also I'm trying to use test-path in order to avoid to create the same folders.
You have several problems in this code.
First you use the $Customer variable in two different contexts. I changed the reference in the ForEach loop to $Cust to eliminate this problem.
You're using formatting commands where simple string expansion will do.
While using PowerShell stick to PowerShell commands, i.e. New-Item vs MkDir.
I'd also suggest indention of your code structures to make reading easier.
NOTE: In the code below I changed your references to $PSScriptRoot to a fixed directory for testing purposes in the PowerShell ISE>
Input File:
Customer,Info
Mickey Mouse,Disney
Iron Man,Marvel
Code:
Clear-Host
$Names = Import-Csv -Path “G:\BEKDocs\Scripts\Info.csv” | Select-Object customer, info
Set-Location -Path "G:\BEKDocs\Scripts\Test\Collection"
foreach($Cust in $Names) {
$CustomerPath = "$($Cust.customer)$($Cust.Info)"
if (Test-Path -Path .\$CustomerPath) {
$Message = "Exists :`t $($Cust.Customer)$($Cust.Info)"
Write-Host $Message -ForegroundColor Green
}
else {
$null = New-Item -Name $CustomerPath -ItemType Directory -Force
$Message = "Created:`t $($Cust.Customer)$($Cust.Info)"
Write-Host $Message -ForegroundColor Red
}
} #End ForEach
Sample Output: (color coding didn't show up when pasted)
Created: Mickey MouseDisney
Exists : Iron ManMarvel