Reputation: 55
I have a CSV file which one of the Colums called Location. It contains "Office CityX" and "Home Office". I want to insert them into AD.
I tried:
$Location = -split $user.Location
$NewLocation = $Location[1]
It's clear that I get City1, City2,… and "Office" But I want "Home Office". How can I split so that I get the cities and also whole "Home Office"?
Upvotes: 0
Views: 67
Reputation: 200293
Split the location only if it contains the word city
:
$NewLocation = if ($user.Location -like '*city*') {
$user.Location.Split()[1]
} else {
$user.Location
}
An alternative (if you have the names of cities instead of the word "city") would be using a regular expression like this:
$NewLocation = if ($user.Location -match 'amsterdam|nairobi|rome|...') {
$user.Location.Split()[1]
} else {
$user.Location
}
or, if it's only the location "Home Office" that you don't want to split, you could do it like this:
$NewLocation = if ($user.Location -ne 'home office') {
$user.Location.Split()[1]
} else {
$user.Location
}
Upvotes: 2
Reputation: 36297
I'll offer an alternative in case it ends up being less City1, City2, City3, and more Orlando, Chicago, Seattle.
RegEx will let you split this easily enough, and will accommodate multi-word city names (rather than ,,Office New York
becoming New
). Plus the -split
method uses regex by default. We'll capture the desired text, so that it is returned from the split and not excluded.
$NewLocation = $_.Location -split ",,(?:Office )?(Home Office|(?<=Office ).+$)"
For a detailed breakdown of this, check out this RegEx101 link.
Now, if we toss a few strings at that it will return either "Home Office" or anything that follows ",,Office ". Examples:
,,Office Seattle
,,Home Office
,,Office Chicago
Becomes:
Seattle
Home Office
Chicago
Upvotes: 1