是否可以根据变量的值来改变它的一部分?
Is it possible to alter part of a variable based on its value?
我有一个脚本可以获取学生组成员的 AD 用户名列表,并将它们分配为 $students
数组
稍后脚本需要获取这些用户名并将它们输入到 URL
$students = Get-ADGroupMember -Identity "GG_LHS All Students" | Select-Object -ExpandProperty SamAccountName | Sort-Object SamAccountName
foreach ($student in $students)
{
foreach ($OneDriveAdmin in $OneDriveAdmins)
Set-SPOUser -Site https://mydomain-my.sharepoint.com/personal/$($student)_mydomain_co_uk
如果我们有重复的用户名,我们的命名方案会以 .1 和 .2 的格式添加增量,但我需要将“.1”更改为“_1”才能在 URL.
我最初的想法是 $students 声明期间的 IF 语句
IF SamAccountName is like '.1' replace '.1' with '_1'
这可以通过 powershell 完成吗?
您可以在循环中添加此检查,如果学生匹配一个点后跟任意数量的数字 (\.(\d+)
),替换为相同的数字,但在前面加上下划线 (-replace $Matches[0], "_$($Matches[1])"
) :
foreach($student in $students) {
if($student -match '\.(\d+)$') {
$student = $student -replace $Matches[0], "_$($Matches[1])"
}
# rest of your code here
}
有关详细信息,请参阅 https://regex101.com/r/fZAOur/1。
提供 , using the (also regex-based)
-replace
运算符的简化替代方案:
# Sample student account names
$students = 'jdoe.1', 'jsixpack', 'jroe.2'
# Transform all names, if necessary, and loop over them.
foreach ($student in $students -replace '\.(?=\d+$)', '_') {
$student
}
正则表达式注释:\.
逐字匹配 .
,而 (?=...)
是一个 look-ahead 断言匹配一个或多个(+
) 数字 (\d
) 在字符串的末尾 ($
)。 look-ahead 断言匹配的内容不会成为整体匹配的一部分,因此仅替换 .
字符就足够了。
输出:
jdoe_1
jsixpack
jroe_2
注:
-replace
- 像 -match
接受一个 array 作为它的 LHS,在这种情况下操作是在 每个元素,并返回一个(通常转换后的)新数组。
如果给定替换操作中 RHS 上的正则表达式不匹配,则输入字符串通过[=44] =](返回 as-is),因此尝试替换与感兴趣模式不匹配的字符串是安全的。
我有一个脚本可以获取学生组成员的 AD 用户名列表,并将它们分配为 $students
数组稍后脚本需要获取这些用户名并将它们输入到 URL
$students = Get-ADGroupMember -Identity "GG_LHS All Students" | Select-Object -ExpandProperty SamAccountName | Sort-Object SamAccountName
foreach ($student in $students)
{
foreach ($OneDriveAdmin in $OneDriveAdmins)
Set-SPOUser -Site https://mydomain-my.sharepoint.com/personal/$($student)_mydomain_co_uk
如果我们有重复的用户名,我们的命名方案会以 .1 和 .2 的格式添加增量,但我需要将“.1”更改为“_1”才能在 URL.
我最初的想法是 $students 声明期间的 IF 语句
IF SamAccountName is like '.1' replace '.1' with '_1'
这可以通过 powershell 完成吗?
您可以在循环中添加此检查,如果学生匹配一个点后跟任意数量的数字 (\.(\d+)
),替换为相同的数字,但在前面加上下划线 (-replace $Matches[0], "_$($Matches[1])"
) :
foreach($student in $students) {
if($student -match '\.(\d+)$') {
$student = $student -replace $Matches[0], "_$($Matches[1])"
}
# rest of your code here
}
有关详细信息,请参阅 https://regex101.com/r/fZAOur/1。
提供 -replace
运算符的简化替代方案:
# Sample student account names
$students = 'jdoe.1', 'jsixpack', 'jroe.2'
# Transform all names, if necessary, and loop over them.
foreach ($student in $students -replace '\.(?=\d+$)', '_') {
$student
}
正则表达式注释:\.
逐字匹配 .
,而 (?=...)
是一个 look-ahead 断言匹配一个或多个(+
) 数字 (\d
) 在字符串的末尾 ($
)。 look-ahead 断言匹配的内容不会成为整体匹配的一部分,因此仅替换 .
字符就足够了。
输出:
jdoe_1
jsixpack
jroe_2
注:
-replace
- 像-match
接受一个 array 作为它的 LHS,在这种情况下操作是在 每个元素,并返回一个(通常转换后的)新数组。如果给定替换操作中 RHS 上的正则表达式不匹配,则输入字符串通过[=44] =](返回 as-is),因此尝试替换与感兴趣模式不匹配的字符串是安全的。