我有一个用户列表,需要授予他们一组Windows服务的访问权限。对于一组定义好的用户,它可以正常工作,但我希望使脚本更加动态化,能够动态传递用户和组名。我可以使用foreach
,但我想要为每个用户在开头添加域名前缀。例如:
$usrs = "abc", "def", "ghi", "jkl"
当我执行 foreach ($usr in $usrs)
时,需要在 "abc"
前缀中添加 "AU\abc"
等。
我有一个用户列表,需要授予他们一组Windows服务的访问权限。对于一组定义好的用户,它可以正常工作,但我希望使脚本更加动态化,能够动态传递用户和组名。我可以使用foreach
,但我想要为每个用户在开头添加域名前缀。例如:
$usrs = "abc", "def", "ghi", "jkl"
当我执行 foreach ($usr in $usrs)
时,需要在 "abc"
前缀中添加 "AU\abc"
等。
$usrs = "abc", "def", "ghi", "jkl"
foreach ($user in $usrs) {
"AU\${user}"
}
$usrs = "abc", "def", "ghi", "jkl"
$usrs.ForEach({"AU\$_"})
一种方法:
$usrs = "abc", "def", "ghi", "jkl" | % { "AU\"+$_ }
foreach($usr in $usrs) {
$user = "AU\$usr"
#Continue script...
}
如果你需要替换现有的数组:
$usrs = $usrs | Foreach-Object { "AU\$_" }
#or
$usrs = foreach($usr in $usrs) { "AU\$usr" }
@("abc", "def", "ghi", "jkl") -replace '^','AU\'
foreach ($i in "abc", "def", "ghi", "jkl") { "AU\$i" }
@("abc", "def", "ghi", "jkl").ForEach{ "AU\$_" }
"abc", "def", "ghi", "jkl" | % { "AU\$_" }
"abc", "def", "ghi", "jkl" | % Insert 0, 'AU\'
"abc", "def", "ghi", "jkl" | % Insert -ArgumentList @(0, 'AU\')
"abc", "def", "ghi", "jkl" | % { $_.Insert(0, 'AU\') }
$usrs = @("abc", "def", "ghi")
$prefixValue = 'AU\'
$usrs | ForEach-Object -Member Insert -ArgumentList @(0, $prefixValue)