Need help in powershell script. - powershell

I have sharepoint 2010 toplevel site with name Test. Under test there are three subsites with name test1, test2, test3 respectively. In top level site (Test) there are three custom group names are: test1group, test2group and test3group.
Using powershell script I want to export the group and permission to their respective subsite. For example if we want to export the group and permission in test1 subsite
then only test1group should be inherited not test2group and test3group..and the similary while performing group export for test2 subsite then, only test2group should be inheriated...not test1group and test2group....and so on(for test3 subsite)..
Using the below scripts I was trying to perform this:
function AddGroupToSite($url, $groupName, $permLevel)
{
$web = Get-SPWeb $url
#Break permissions inheritance and copy the groups from parent site into this site (recommended)
$web.BreakRoleInheritance($true)
$web.Update()
#Creating a new group:
$web.SiteGroups.Add($groupName, $web.Site.Owner, $web.Site.Owner, "New Group from powershell 4")
$newGroup = $web.SiteGroups[$groupName]
#Create role assignment:
$newGroupAssign = New-Object Microsoft.SharePoint.SPRoleAssignment($newGroup)
#Assign a specific role
#The possible enumeration values are: None, Guest, Reader, Contributor, WebDesigner, Administrator
$newGroupAssign.RoleDefinitionBindings.Add($web.RoleDefinitions.GetByType($permLevel))
$web.RoleAssignments.Add($newGroupAssign)
#Update web
$web.Update()
$web.Dispose()
}
But everytime its inhereting all the group from top level site(which is default behavior)....Can we customize the powershell script so that we can achieve the above functionality..Any help is highly appreciated.

When you break the inheritance, it creates a copy of what was originally inherited.
I don't have the Sharepoint commands handy, but you should be able to do something like
function Remove-SPGroup ($url, $groupName)
{
$web = Get-SPWeb $url
$web.SiteGroups.Remove($GroupName)
$web.Update()
$web.dispose()
}
to remove the initially inherited groups.
So you could add this to your existing script and have something like
function AddGroupToSite($url, $groupName, $permLevel)
{
$web = Get-SPWeb $url
#Break permissions inheritance and copy the groups from parent site into this site (recommended)
$web.BreakRoleInheritance($true)
$web.Update()
#Creating a new group:
$web.SiteGroups.Add($groupName, $web.Site.Owner, $web.Site.Owner, "New Group from powershell 4")
$newGroup = $web.SiteGroups[$groupName]
foreach ($ExistingGroup in $web.SiteGroups)
{
if ($ExistingGroup.name -notlike $groupname)
{
$web.SiteGroups.Remove($ExistingGroup.name)
}
}
#Create role assignment:
$newGroupAssign = New-Object Microsoft.SharePoint.SPRoleAssignment($newGroup)
#Assign a specific role
#The possible enumeration values are: None, Guest, Reader, Contributor, WebDesigner, Administrator
$newGroupAssign.RoleDefinitionBindings.Add($web.RoleDefinitions.GetByType($permLevel))
$web.RoleAssignments.Add($newGroupAssign)
#Update web
$web.Update()
$web.Dispose()
}

Related

Azure DevOps Get Current User ObjectId

Is there a way to get the ObjectId of the Service Principal that is currently executing an Azure PowerShell task in Azure DevOps at all?
I am creating a resource, and then want to apply permissions for the 'current' user.. but can't work out how to get the current user ObjectId / ApplicationId
Is this possible?
Ok - based of the above, I've made a little function - it may work for a lot of cases:
function Get-CurrentUserObjectID {
$ctx = Get-AzContext
#This is different for users that are internal vs external
#We can use Mail for users and guests
$User = Get-AzADUser -Mail $ctx.Account.id
if (-not $user) { #Try UPN
$User = Get-AzADUser -UserPrincipalName $ctx.Account.Id
}
if (-not $User) { #User was not found by mail or UPN, try MailNick
$mail = ($ctx.Account.id -replace "#","_" ) + "#EXT#"
$User = Get-AzADUser | Where-Object { $_MailNick -EQ $Mail}
}
Return $User.id
}
There seems to be two ways of doing this depending on if it's a user, or a service principal:-
Get-AzADUser
Get-AzADServicePrincipal
These i believe are in the Az.Resources module. So, to give you the ObjectId (for permissions), you could take a two step approach like this:
$x = (Get-AzContext).Account.Id
$x
> df6fc4f6-cb05-4301-91e3-11d93d7fd43d # ApplicationId
$y = Get-AzADServicePrincipal -ApplicationId $x
$y.Id
> c3588e6a-b48b-4111-8241-3d6bd726ca40 # ObjectId
I can't get anything to work reliably with standard users though.. if your user is created in the AzureAD directly, and not external (i.e. gmail.com, outlook.com, etc) this should work:
$x = (Get-AzContext).Account.Id
$x
> sample#your-domain.onmicrosoft.com # UserPrincipalName
$y = Get-AzADUser -UserPrincipalName $x
$y.Id
> c5d4339b-48dc-4190-b9fb-f5397053844b # ObjectId
If your user is external, and has the weird your.email.address_outlook.com#EXT##your-domain.onmicrosoft.com as the UserPrincipalName you'll need to solve that with a bit of string manipulation i think 😕.
But! You shouldn't be scripting things with user accounts anyway, so it probably doesn't matter 😆.
Note: I have not tried this in Azure DevOps, you will probs need to upgrade the PowerShell packages, but i think the same commands should exist as Get-AzureRmADUser, and Get-AzureRmADServicePrincipal. Please let me know.

Add user in domain1 to domain2 group with powershell?

I am looking for some powershell code that can add a user from one domain to another domain group. I can't seem to find the magic code that will work that uses System.DirectoryServices.
###############
# Query user
################
# Variables
$path="GC://ldap-server.company.com"
# To limit the information returned add properties. Use an empty string to
pull everything
$property="objectcategory,distinguishedname,cn,mailnickname,samaccountname"
$searchFilter="(&(objectClass=User)(samaccountname=joker))"
$rootEntry = New-Object System.DirectoryServices.DirectoryEntry $path
$search= New-Object System.DirectoryServices.DirectorySearcher $rootEntry;
if ($properties) {
foreach ($property in [regex]::split($properties, ", ?")) {
[void]$search.PropertiesToLoad.Add($property);
}
}
$search.Filter = $searchFilter;
$searchResults = $search.FindOne();
$user = $searchResults.GetDirectoryEntry()
$user_dn = $searchResults.GetDirectoryEntry().distinguishedName;
# to find the first or only result, use $searchResults = $search.FindOne();
################
#Query group
################
# Same as Query user, just change
$property="";
$searchFilter="(&(objectClass=Group)(samaccountname=mygroup))";
$search.Filter = $searchFilter;
$searchResults = $search.FindOne();
################
#Add user to group
################
# From your group query
$group_dn = $searchResults.GetDirectoryEntry().distinguishedName
I tried this, but it did not seem to add the user and is ADSI:
$Group = [ADSI]"LDAP://"+$group_dn
$User = [ADSI]"LDAP://"+$user_dn
If ($Group.IsMember($User.ADsPath) -eq $False)
{
$Group.Add($User.ADsPath)
}
I was unfortunate enough to have to do this the hard way once (a domain migration where the source domain was still on Windows Server 2008). What you need to do is add the user or group from the remote domain as a foreign security principal:
...
$group_dn = $searchResults.GetDirectoryEntry().distinguishedName
$fsp = New-Object Security.Principal.NTAccount('DOM1', 'username')
$sid = $fsp.Translate([Security.Principal.SecurityIdentifier]).Value
$group = New-Object DirectoryServices.DirectoryEntry("LDAP://$group_dn")
[void]$group.Member.Add("<SID=$sid>")
$group.CommitChanges()
$group.Close()
If possible you should use the ActiveDirectory module (requires at least Windows Server 2008 R2 and access to the AD Web Services).

Powershell list group membership of user (Novell eDirectory) NDS LDAP

Trying to figure out, how to map a network share based on group membership of Novell eDir.
I found a smart script in Technet for ActiveDirectory via ADSISEARCHER which is working pretty well in AD :)
# extract group names and removes unnecessary characters
$memberOf = ([ADSISEARCHER]"samaccountname=$($env:USERNAME)").Findone().$does.memberof -replace '^CN=([^,]+).+$','$1'
# check if user is member of group A
if($memberOf -contains "GroupA") {
# map network-drive
(New-Object -ComObject WScript.Network).MapNetworkDrive('X:','\\filer\sharename')
}
Is there any chance to use something similar for NDS?
As far as I researched I have to use LDAP to connect to NDS and list all groups of a user object, but haven't much luck yet.
Thx
I found a useful script out there which I just have to edit a littlebit...
URL to Script:
http://activedirectoryfaq.com/2014/01/searching-novell-nds-edirectory-with-powershell/
My final script in case somebody needs this crap:
<#
.SYNOPSIS
Mapping a network share based on a specific group membership in NDS
.DESCRIPTION
The script is mapping a network drive, based on a NDS group membership.
The first match wins!
#>
# --------<SET CORRESPONDING VALUES HERE >--------
# Hostname of eDir Server (e.g.: NDSSRV01):
$LDAPServer = "hostname"
# Name of BaseDN (e.g.: o=MyCompany):
$dn = "o=basedn"
# ------------------------------------------------
# set username of current logged on user
$filter = "(uid=$env:USERNAME)"
# Creating necessary objects
[reflection.assembly]::LoadWithPartialName("system.directoryservices.protocols") | out-null
$ldapIdentifier = new-object directoryservices.protocols.ldapdirectoryidentifier($LDAPServer)
$ldapConnection = new-object directoryservices.protocols.ldapconnection($ldapIdentifier,$null,0)
# Attributes to search for:
# To search for multiple use comma separated list (eg: "groupmembership","cn","emailAddress")
[string[]]$attr = "groupmembership"
# Establishing LDAP connection
$scope = $ADS_SCOPE_SUBTREE
$searchRequest = new-object directoryservices.protocols.searchrequest($dn,$filter,$ADS_SCOPE_SUBTREE,$attr)
$searchRequest.typesonly = $false
$searchRequest.sizelimit = 10
$result = [directoryservices.protocols.searchresponse]$ldapConnection.sendrequest($searchRequest)
$entry = $result.entries
# extract group names and removes unnecessary characters
$membership = $entry[0].Attributes["groupmembership"].getValues([string]) -replace '^CN=([^,]+).+$','$1'
# check if user is member of group A
if($membership -contains "GroupA") {
# map network-drive
(New-Object -ComObject WScript.Network).MapNetworkDrive('X:','\\filer\sharegroupa')
}
# check if user is member of group B
elseif($membership -contains "GroupB") {
# map network-drive
(New-Object -ComObject WScript.Network).MapNetworkDrive('X:','\\filer\sharegroupb')
}
# elseif() ... and so on
# if nothing matches, then:
else {
Write-Host 'current user is not a member of a specified group'
}

Create Libraries and Permissions with SharePoint Powershell

I'm trying to make a script to help automate this process a bit but am fairly new to using PowerShell with SharePoint and don't really know the route to take.
I have a list of 40 items and I need to make a library for each one. Each library then needs to have unique permissions with 3 default groups(Owners, Members, Visitors). The groups should be named the same as the List.Title + Owners/Members/Visitors.
So far I create a site group as follows:
# Owner Group
$web.SiteGroups.Add(“$web Owners”, $web.Site.Owner, $web.Site.Owner, “Use this group to grant people full control permissions to the $web site”)
$ownerGroup = $web.SiteGroups["$web Owners"]
$ownerGroup.AllowMembersEditMembership = $true
$ownerGroup.Update()
The naming of my groups needs to be the list title and not the web name as I have above.
I create a new library like this:
PS > $spWeb = Get-SPWeb -Identity http://SPServer
PS > $listTemplate = [Microsoft.SharePoint.SPListTemplateType]::DocumentLibrary
PS > $spWeb.Lists.Add("My Documents","My Doc Library",$listTemplate)
Clearly this is not automated at all and no faster than just using the GUI to make each new library and adding in the site groups. Can anyone help get me started on a script that would iterate through a list of names create a library and create 3 groups on the site for each new library?
Thanks!!
This should get you on the right track I believe.
Add-PSSnapin "Microsoft.SharePoint.PowerShell"
$Lists = #("My Documents", "My Docs", "Testing")
$Groups = #("Owners", "Members", "Visitors")
$listTemplate = [Microsoft.SharePoint.SPListTemplateType]::DocumentLibrary
$Web = Get-SPWeb "Your_URL"
$Lists | ForEach-Object {
$ListName = $_
$Description = "$_ Description"
$Web.Lists.Add($ListName, $Description, $listTemplate)
$Groups | % {
$GroupName = "$ListName $_"
$Web.SiteGroups.Add($GroupName, $Web.Site.Owner, $Web.Site.Owner, "Group $GroupName created by automatic process")
$group = $Web.SiteGroups["$GroupName"]
if ( !$GroupName -contains "Visitors")
{
$group.AllowMembersEditMembership = $true
} else
{
$group.AllowMembersEditMembership = $false
}
$group.Update()
}
}

How to update local user groups user name?

Our application will add list of user in local user groups.
Users will be associated with the groups , if the user name is changed we may need to update them in groups.
I was trying to use [ADSI] in powershell to get the list first then modify it .
$MyprojGroups=#("Myproj Engineers",
"Myproj Managers",
"MyprojDBUser",
"MyprojUser")
Foreach( $MyprojGroup in $MyprojGroups) {
Write-host "MyprojGroup : $MyprojGroup "
$usergroup=[ADSI]($MyprojGroup).psbase.Path
$usergroup
UpdateUserName -groupName $usergroup -OlduserName "Administrator" -NewuserName "Admin"
}
Function UpdateUserName {
Param (
[string]$OlduserName,
[string]$groupName,
[string]$NewuserName
)
# To check whether the user name is associated with the group
$MEm=$groupName.psbase.Invoke("Members") | foreach {$_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null)}
If ($mem -eq "OlduserName") {
# Has to update the New User Name
}
}
But passing the groupname directly is not being accepted for ADSI. How to update the user name if it associated with the assigned groups?
do you run your powershell script on each computer you want to check ?
Do you want to add local users to the local groups ?
can you try something like (within administrator shell of course) :
$grp = [ADSI]"WinNT://$computerName/$groupName,group"
$grp.add("WinNT://$computerName/$NewUserName")
$grp.remove("WinNT://$computerName/$OldUserName")