Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 962
Karthik Avatar asked Oct 22 '25 03:10

Karthik


2 Answers

One way to do it:

$usrs = "abc", "def", "ghi", "jkl" | % { "AU\"+$_ }
like image 198
Micky Balladelli Avatar answered Oct 23 '25 18:10

Micky Balladelli


This should help.

$usrs = "abc", "def", "ghi", "jkl"
foreach ($user in $usrs) {
    "AU\${user}"
}

Also, starting PowerShell 4.0, you can do this as well.

$usrs = "abc", "def", "ghi", "jkl"
$usrs.ForEach({"AU\$_"})
like image 43
ravikanth Avatar answered Oct 23 '25 16:10

ravikanth