Reputation: 47
Location.csv Sample I'm trying to create a single folder by prompting the user for userID and the group used to map the home folder.
The below script creates the user's home folder in each location and not in the location matching the prompt.
Running the script without the foreach loop doesn't work.
$Locations = Import-Csv "C:\Scripts\CreateHomeFolder\Location.csv"
$UserName = Read-Host "Enter User Logon Name"
$UserGroup = Read-Host "Enter User's Home drive group"
foreach($Location in $Locations.Location){
if ($Locations.Groups -eq $UserGroup){
New-Item -Name $UserID -Path $Locations.Location -ItemType Directory -Verbose
}
}
what am I doing wrong here?
Upvotes: 0
Views: 610
Reputation: 437197
Theo's helpful answer addresses your immediate problem.
Your own answer improves on your original approach, though by not using
select -ExpandProperty Location
- note the use of -ExpandProperty
(select
is the built-in alias for the Select-Object
cmdlet) - it creates unnecessary duplication (and processing overhead) by having to refer to Location
twice.
Another option is to use direct property access:
New-Item -Name $UserName -ItemType Directory -Verbose -Path (
(
Import-Csv C:\Scripts\CreateHomeFolder\Locations.csv |
Where-Object Groups -eq $UserGroup
).Location
)
Upvotes: 0
Reputation: 47
went back to the drawing board, refined my google search and found the solution to be:
$Locations = Import-Csv "C:\Scripts\CreateHomeFolder\Locations.csv" | Where-Object Groups -eq $UserGroup | select Location
New-Item -Name $UserName -Path $Locations.Location -ItemType Directory -Verbose
Upvotes: 0
Reputation: 61028
As commented, you have the variables wrong. The iterating variable is $location
and in each iteration it is an object taken from the array $locations
.
Use
foreach($Location in $Locations){
if ($Location.Groups -eq $UserGroup){
New-Item -Name $UserID -Path $Location.Location -ItemType Directory -Verbose
}
}
Upvotes: 1