在 Powershell 中为每个数组值添加一个字符串前缀
Prefix a string for each array values in Powershell
我有一个用户列表,我需要授予对一组 Windows 服务的访问权限。它适用于一组定义的用户,但我想让脚本更加动态并动态传递用户名和组名。我可以做到 foreach
,但我希望能够在每个用户的开头添加域名前缀。示例:
$usrs = "abc", "def", "ghi", "jkl"
当我执行 foreach ($usr in $usrs)
时,它需要在 "abc"
前加上 "AU\abc"
等等。
一种方法:
$usrs = "abc", "def", "ghi", "jkl" | % { "AU\"+$_ }
这应该有所帮助。
$usrs = "abc", "def", "ghi", "jkl"
foreach ($user in $usrs) {
"AU${user}"
}
此外,从 PowerShell 4.0 开始,您也可以这样做。
$usrs = "abc", "def", "ghi", "jkl"
$usrs.ForEach({"AU$_"})
你可以试试这个:
foreach($usr in $usrs) {
$user = "AU$usr"
#Continue script...
}
或者如果您需要替换现有数组:
$usrs = $usrs | Foreach-Object { "AU$_" }
#or
$usrs = foreach($usr in $usrs) { "AU$usr" }
我有一个用户列表,我需要授予对一组 Windows 服务的访问权限。它适用于一组定义的用户,但我想让脚本更加动态并动态传递用户名和组名。我可以做到 foreach
,但我希望能够在每个用户的开头添加域名前缀。示例:
$usrs = "abc", "def", "ghi", "jkl"
当我执行 foreach ($usr in $usrs)
时,它需要在 "abc"
前加上 "AU\abc"
等等。
一种方法:
$usrs = "abc", "def", "ghi", "jkl" | % { "AU\"+$_ }
这应该有所帮助。
$usrs = "abc", "def", "ghi", "jkl"
foreach ($user in $usrs) {
"AU${user}"
}
此外,从 PowerShell 4.0 开始,您也可以这样做。
$usrs = "abc", "def", "ghi", "jkl"
$usrs.ForEach({"AU$_"})
你可以试试这个:
foreach($usr in $usrs) {
$user = "AU$usr"
#Continue script...
}
或者如果您需要替换现有数组:
$usrs = $usrs | Foreach-Object { "AU$_" }
#or
$usrs = foreach($usr in $usrs) { "AU$usr" }