需要有关如何遍历脚本的帮助

时间:2019-07-11 22:01:43

标签: powershell loops for-loop

我有一些要运行的代码,这是一个Powershell脚本,可创建网络共享,分配权限并向安全组添加权限,并向该组添加用户。我已经构建了代码并对其进行了测试,并且它可以正常工作,但是现在我需要使用名为samAccountName的变量将其循环为CSV中的用户列表

添加了一个我还没有尝试过的简单示例,我没有测试环境

Import-Csv "C:\Users\bhabib\makeshares.csv" | ForEach-Object {
New-ADOrganizationalUnit -Name $_."samAccountName" -Path "OU=user,DC=domain,DC=com,DC=com"
New-ADGroup -Name "Write_share_$($_."samAccountName")" -GroupCategory Security -GroupScope Domain -DisplayName "Write_Share_$($_."samAccountName")" -Path "OU=$($_."samAccountName"),OU=user,OU=blabla,DC=domain,Dc=domain,DC=com"
New-ADGroup -Name "Read_share_$($_."samAccountName")" -GroupCategory Security -GroupScope Domain -DisplayName "Read_Share_$($_."samAccountName")" -Path "OU=$($_."samAccountName"),OU=user,OU=blabla,DC=domain,DC=domain,DC=com"
New-Item -Path "D:\Shares\$($_."samAccountName")\MyDocuments" -ItemType "directory" -Force
$securitygroupwrite = "Write_share_$($_."samAccountName")"
$securitygroupread = "Read_share_$($_."samAccountName")"
New-SMBShare -Name $_."samAccountName" -Path "D:\Shares\$($_."samAccountName")\MyDocuments" -FullAccess "Administrators" -ChangeAccess $securitygroupwrite -ReadAccess $securitygroupread
Add-ADPrincipalGroupMembership -Identity $_."samAccountName" -MemberOf "Write_share_$($_."samAccountName")"
Add-ADPrincipalGroupMembership -Identity $_."samAccountName" -MemberOf "Read_share_$($_."samAccountName")"
$acl = Get-Acl "D:\Shares\$($_."samAccountName")\MyDocuments"
$AccessRuleWrite = New-Object System.Security.AccessControl.FileSystemAccessRule(“UPN\Write_share_$($_."samAccountName")","FullControl","ContainerInherit, ObjectInherit", "None","Allow")
$AccessRuleExecute = New-Object System.Security.AccessControl.FileSystemAccessRule(“UPN\Read_share_$($_."samAccountName")","ReadAndExecute","ContainerInherit, ObjectInherit", "None","Allow")
$AccessRuleRead = New-Object System.Security.AccessControl.FileSystemAccessRule(“UPN\Read_share_$($_."samAccountName")","Read","ContainerInherit, ObjectInherit", "None","Allow")
$acl.SetAccessRule($AccessRuleWrite)
$acl.SetAccessRule($AccessRuleRead)
$acl.SetAccessRule($AccessRuleExecute)
$acl | Set-Acl 
$acl = Get-Acl "D:\Shares\$($_."samAccountName")\MyDocuments"
}

1 个答案:

答案 0 :(得分:1)

您应该始终具有测试环境。 活动目录很难通过快照还原。我真的建议您构建一个测试环境。这并不难,您也不会后悔。

但是看起来您的for循环设置正确。您不需要在samAccountName变量周围加上引号。但这确实伤害了。

如果您使用-Server参数明确列出域控制器,您的脚本可能会更稳定。

您可以使用-whatif参数来辅助测试过程。