arraysvariablespowershellprefix

Prefix a string for each array values in Powershell


I have a list of users that I need to grant access to a set of Windows services. It works well for a defined set of users, but I want to make the script more dynamic and pass the user and group names dynamically. I can do foreach, but I want to be able to prefix domain name at the beginning for each users. Example:

$usrs = "abc", "def", "ghi", "jkl"

When I do foreach ($usr in $usrs) it needs to prefix "abc" with "AU\abc" and so on.


Solution

  • You could try this:

    foreach($usr in $usrs) {
        $user = "AU\$usr"
        #Continue script...
    }
    

    Or if you need to replace the existing array:

    $usrs = $usrs | Foreach-Object { "AU\$_" }
    #or
    $usrs = foreach($usr in $usrs) { "AU\$usr" }