I’ve used loops to perform repeated tasks before but hit a snag with one that I wanted to do. It’s easy to vary an object with a number variable. For example:
1..4 | Foreach-object {Get-ExchangeServer -Identity SERVER0"$_"}
returns SERVER01, SERVER02, SERVER03, SERVER04.
Simples as Bob would say.
But trying to do that in a command that is already incorporating quotes (because there are spaces) poses a new dilemma. What am I on about? Look at the following example:
Set-OWAVirtualDirectory -Identity "SERVER0"$_"\OWA (Default Web Site)" -ExternalUrl https://mail.company.com/owa
That won’t work.
Don’t panic Mr Mainwaring, don’t panic
I have a solution and it works a treat. Break up the text and define it as a variable(s). Like this:
$dir = "\OWA (Default Web Site)"; 1..4 | Foreach-object {Set-OWAVirtualDirectory -Identity SERVER0"$_"$dir -ExternalUrl https://mail.company.com/owa}
So that one liner basically does this:
Set-OWAVirtualDirectory -Identity SERVER01\OWA (Default Web Site) -ExternalUrl https://mail.company.com/owa
Set-OWAVirtualDirectory -Identity SERVER02\OWA (Default Web Site) -ExternalUrl https://mail.company.com/owa
Set-OWAVirtualDirectory -Identity SERVER03\OWA (Default Web Site) -ExternalUrl https://mail.company.com/owa
Set-OWAVirtualDirectory -Identity SERVER04\OWA (Default Web Site) -ExternalUrl https://mail.company.com/owa