See users who visited sharepoint site Search-UnifiedAuditLog - sharepoint

Im trying to export a list of users who have visited the different sharepoint sites in my collection. I have tried and i can get it to work with internal users but not for external.
$startdate = "11/10/2017 8:00 AM"
$enddate = "11/10/2017 9:00 AM"
$userIDs = (import-csv C:\Junk\User.csv).Email
foreach ($userid in $userids) {
$AuditlogMain = Search-UnifiedAuditLog -StartDate $startdate -EndDate $enddate -RecordType SharePoint -Operations PageViewed -UserIds $userID -ObjectIds "https://sitename.sharepoint.com/" -Formatted
$AuditlogMain.UserIDs | Select-object -Unique | Out-File C:\junk\Main.csv -Append
}
I then get a list of unique users but i want to list all the external users also and i don't know how to simply change the mail from "#.com" to _.com#EXT##.onmicrosoft.com
Or is there a more simple way to export the users that have visited a site?
If you look in $AuditlogMain.AuditData there are some more information i want but i don't know how to extract it. So if someone could help me with the external users or more preferably help me extract ClientIP, ObjectId, UserId from $AuditlogMain.AuditData that would be helpful.
Thanks in advance

Excerpts from the article provided:
$cred = Get-Credential
$session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $cred -Authentication Basic -AllowRedirection
Import-PSSession $session
Connect-MsolService -Credential $cred
$extUsers = Get-MsolUser | Where-Object {$_.UserPrincipalName -like "*#EXT#*" }
$extUsers | ForEach {
$auditEventsForUser = Search-UnifiedAuditLog -EndDate $((Get-Date)) -StartDate $((Get-Date).AddDays(-7)) -UserIds $_.UserPrincipalName
Write-Host "Events for" $_.DisplayName "created at" $_.WhenCreated
$auditEventsForUser | FT
}
Remove-PSSession $session
Here's an article that explains how to get audit info for external users:
https://www.sharepointappie.nl/using-powershell-to-get-audit-data-for-external-users/

Related

Get-PnPTenantSite : Attempted to perform an unauthorized operation

Currently we get an access token and then pass this token to PowerShell script to loop across all ODFB personal sites.
$url = "https://XXXXX-admin.sharepoint.com"
$conn = Connect-PnPOnline -Url $url -AccessToken $access_token -ReturnConnection
$sitecollections = Get-PnPTenantSite -IncludeOneDriveSites:$true -Filter "Url -like '-my.sharepoint.com/personal/'" -Connection $conn | Select-Object -ExpandProperty Url
foreach ($site in $sitecollections)
{
....
}
It worked successfully for years until it was broken a while ago.
I tried different versions of PnP PowerShell:
PnP version
Error
SharePointPnPPowerShellOnline 3.21.2005.2 (currently used)
Get-PnPTenantSite : Attempted to perform an unauthorized operation.
SharePointPnPPowerShellOnline 3.29.2101.0
Get-PnPTenantSite : The current connection holds no SharePoint context.
PnP.PowerShell 1.10.28
Get-PnPTenantSite : Attempted to perform an unauthorized operation.
If I change script to use an user/password instead the access token, the script works without problems:
$url = "https://XXXXX-admin.sharepoint.com"
$User = "admin#mydomain.com"
$PWord = ConvertTo-SecureString -String "Password" -AsPlainText -Force
$Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, $PWord
$conn = Connect-PnPOnline -Url $url -Credentials $Credential -ReturnConnection
$sitecollections = Get-PnPTenantSite -IncludeOneDriveSites:$true -Filter "Url -like '-my.sharepoint.com/personal/'" -Connection $conn | Select-Object -ExpandProperty Url
foreach ($site in $sitecollections)
{
....
}
So the error happens when the script connects to SP Online using an access token.
Perhaps the some things were changed. But what exactly? Have some scope to be added when an access token is requested?
Or have some new permissions to be added for the application in Azure AD?
Update:
Modified the script (added Write-Output "Connection is:" $conn | fl) to provide more details about connection and got the difference in ConnectionType property when SharePointPnPPowerShellOnline 3.21.2005.2 is used:
When an access token is used (and the script doesn't work properly), ConnectionType : O365
When an access token is used (and the script works fine), ConnectionType : TenantAdmin

Win Server ADGroup Security Access Control

I would like to create a user on Win Server 2022, without admin rights, who can modify the content of administrator groups.
I have added this user a full control over these groups with a PS script, but after a while, Windows automatically removes my user from there.
Is threre a way to stay there permanently?
$PWord = ConvertTo-SecureString -String "# ... #" -AsPlainText -Force
New-ADUser -Name "creator" -SamAccountName "creator" -UserPrincipalName "creator" -DisplayName "creator" -Enabled $true -AccountPassword $PWord -ChangePasswordAtLogon $false -PasswordNeverExpires $true
Add-AdGroupMember -Identity "S-1-5-32-548" -Members "creator"
Add-AdGroupMember -Identity "S-1-5-32-580" -Members "creator"
New-ADOrganizationalUnit -Name "MyDomain"
enable-psremoting -Force
$sid = (Get-ADDomain -Server 127.0.0.1 | Select DomainSID | ft -HideTableHeaders | out-string).Trim()
$groups = #("S-1-5-32-544",$($sid+"-512"),$($sid+"-518"),$($sid+"-519"),$($sid+"-520"))
$colRights = [System.DirectoryServices.ActiveDirectoryRights]"GenericAll"
$objType =[System.Security.AccessControl.AccessControlType]::Allow
$objUser = New-Object System.Security.Principal.NTAccount("creator")
$objACE = New-Object System.DirectoryServices.ActiveDirectoryAccessRule ($objUser, $colRights, $objType)
foreach($group in $groups)
{
$objACL=Get-ACL "AD:$((get-adgroup $group).DistinguishedName)"
$objACL.AddAccessRule($objACE)
Set-ACL "AD:$((get-adgroup $group).DistinguishedName)" $objACL
}
$OU = (Get-ADOrganizationalUnit -Filter {Name -eq 'MyDomain'}).DistinguishedName
$ouACL=Get-ACL "AD:$OU"
$ouACL.AddAccessRule($objACE)
Set-ACL "AD:$OU" $ouACL

How to activate Privileged Access Groups using Powershell?

I am trying to activate my privileged access groups using powershell however so far unable to do so. All the examples either in MS Docs site or google search only have examples regarding instruction to activate roles using powershell for PIM.
Has anyone been successful or have an idea how to get privileged access groups activated using powershell?
Here is what i tried:
#variables
$upn = ""
$tenantId = ""
$reason = "Test"
$groupId = "" #privileged access groups Id retrieved from Azure Portal > Groups > <group which has roles>
#MFA setup
if(!(Get-Module | Where-Object {$_.Name -eq 'PowerShellGet' -and $_.Version -ge '2.2.4.1'})) { Install-Module PowerShellGet -Force }
if(!(Get-Package msal.ps)) { Install-Package msal.ps }
# Get token for MS Graph by prompting for MFA
$MsResponse = Get-MSALToken -Scopes #("https://graph.microsoft.com/.default") -ClientId "1b730954-1685-4b74-9bfd-dac224a7b894" -RedirectUri "urn:ietf:wg:oauth:2.0:oob" -Authority "https://login.microsoftonline.com/common" -Interactive -ExtraQueryParameters #{claims='{"access_token" : {"amr": { "values": ["mfa"] }}}'}
# Get token for AAD Graph
$AadResponse = Get-MSALToken -Scopes #("https://graph.windows.net/.default") -ClientId "1b730954-1685-4b74-9bfd-dac224a7b894" -RedirectUri "urn:ietf:wg:oauth:2.0:oob" -Authority "https://login.microsoftonline.com/common"
Connect-AzureAD -AadAccessToken $AadResponse.AccessToken -MsAccessToken $MsResponse.AccessToken -AccountId: $upn -tenantId: $tenantId
$roleDefinitionCollection = Get-AzureADMSPrivilegedRoleAssignment -ProviderId "aadRoles" -ResourceId $resource.Id -Filter "subjectId eq '$grouipId'"
#set schedule
$schedule = New-Object Microsoft.Open.MSGraph.Model.AzureADMSPrivilegedSchedule
$schedule.Type = "Once"
$schedule.StartDateTime = (Get-Date).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffZ")
$schedule.endDateTime = (Get-Date).AddHours($activateTime).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffZ")
$subject = Get-AzureADUser -Filter "userPrincipalName eq '$upn'"
foreach ($roleDefinition in $roleDefinitionCollection) {
Open-AzureADMSPrivilegedRoleAssignmentRequest -ProviderId AadRoles -Schedule $schedule -ResourceId $resource.Id -RoleDefinitionId $roleDefinition.RoleDefinitionId -SubjectId $subject.ObjectId -AssignmentState "Active" -Type "UserAdd" -Reason $reason
}
This returns error message:
Open-AzureADMSPrivilegedRoleAssignmentRequest : Error occurred while executing OpenAzureADMSPrivilegedRoleAssignmentRequest
Code: RoleAssignmentDoesNotExist
Message: The Role assignment does not exist.
InnerError:
RequestId: b6e750c4-acf4-4032-84ea-29d74fbc53ac
DateTimeStamp: Fri, 25 Mar 2022 19:00:10 GMT
HttpStatusCode: NotFound
HttpStatusDescription: Not Found
HttpResponseStatus: Completed
At line:2 char:5
+ Open-AzureADMSPrivilegedRoleAssignmentRequest -ProviderId AadRole ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Open-AzureADMSP...signmentRequest], ApiException
+ FullyQualifiedErrorId : Microsoft.Open.MSGraphBeta.Client.ApiException,Microsoft.Open.MSGraphBeta.PowerShell.OpenAzureADMSPrivilegedRoleAssignmentRequest
These were some of the sites that i referred: (all only have example to activate the role)
http://www.anujchaudhary.com/2020/02/connect-to-azure-ad-powershell-with-mfa.html
https://learn.microsoft.com/en-us/azure/active-directory/privileged-identity-management/powershell-for-azure-ad-roles#activate-a-role-assignment
https://www.youtube.com/watch?v=OVfwO8_eDjs
Edit: Sorry I misread some part of your question actually.
In fact, you should adapt the provider id to "aadGroups" in order to use the group features.
This should help you to be on track depending on your environment:
$groupId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
$upn="myyupn#domain.com"
Connect-AzureAD
$resource = Get-AzureADMSPrivilegedResource -ProviderId aadGroups
$subject = Get-AzureADUser -Filter "userPrincipalName eq '$upn'"
# here you will require some additionnal filtering depending on your environment
$roleDefinitionCollection = Get-AzureADMSPrivilegedRoleDefinition -ProviderId "aadGroups" -ResourceId $groupId
#this works only when pimed in my case:
#$roleDefinitionCollection = Get-AzureADMSPrivilegedRoleAssignment -ProviderId "aadGroups" -ResourceId $resource.id -Filter "ResourceId eq '$groupId' and AssignmentState eq 'Eligible'"
$reason = "test"
foreach ($roleDefinition in $roleDefinitionCollection) {
$schedule = New-Object Microsoft.Open.MSGraph.Model.AzureADMSPrivilegedSchedule
$schedule.Type = "Once"
$schedule.Duration="PT1H"
$schedule.StartDateTime = (Get-Date).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffZ")
Open-AzureADMSPrivilegedRoleAssignmentRequest -ProviderId "aadGroups" -Schedule $schedule -ResourceId $groupId -RoleDefinitionId $roleDefinition.id -SubjectId $subject.ObjectId -AssignmentState "Active" -Type "UserAdd" -Reason $reason
}
When you try to assign the Role, it will be
You Can't be assigned for a duration of less than five minutes.
You Can't be removed within five minutes of it being assigned
Here is your script, you need to wait for 5 minutes for every iteration to create a Group Role Assignment
foreach ($roleDefinition in $roleDefinitionCollection) {
Open-AzureADMSPrivilegedRoleAssignmentRequest -ProviderId AadRoles -Schedule $schedule -ResourceId $resource.Id -RoleDefinitionId $roleDefinition.RoleDefinitionId -SubjectId $subject.ObjectId -AssignmentState "Active" -Type "UserAdd" -Reason $reason
# wait for 5 minutes
Start-Sleep -s 300
}
Refer here for more information

UserLastLogon -Export

Hi I'm trying to export a list of AD users based on "Last Logon"
I've scripted using base powershell however I'd be interested if anyone can find a solution using "AzureAD to Powershell" commands.
I've gotten as far as getting the list however I cannot export it to any file type because of how it generates through the loop.
End result I'm looking for is to be able to organize the data to see which users have been inactive?
Import-Module ActiveDirectory
function Get-ADUserLastLogon([string]$userName) {
$dcs = Get-ADDomainController -Filter {Name -like "*"}
$time = 0
foreach($dc in $dcs) {
$hostname = $dc.HostName
$user = Get-ADUser $userName | Get-ADObject -Properties lastLogon
if($user.LastLogon -gt $time) {
$time = $user.LastLogon
}
}
$dt = [DateTime]::FromFileTime($time)
Write-Host $username "last logged on at:" $dt
}
$unames = Get-ADUser -Filter 'ObjectClass -eq "User"' | Select -Expand SamAccountName
foreach ($uname in $unames) { Get-ADUserLastLogon($uname); }
In Azure AD, we can get all user Sign-ins records on Azure Portal or using Azure AD PowerShell.
If you are looking for a way by PowerShell to export Azure AD users last login list with user account status (enabled or not), just try the code below:
Connect-AzureAD
$AllUsers = Get-AzureADUser -All $true
$AllSiginLogs = Get-AzureADAuditSignInLogs -All $true
$results = #()
foreach($user in $AllUsers){
$LoginRecord = $AllSiginLogs | Where-Object{ $_.UserId -eq $user.ObjectId } | Sort-Object CreatedDateTime -Descending
if($LoginRecord.Count -gt 0){
$lastLogin = $LoginRecord[0].CreatedDateTime
}else{
$lastLogin = 'no login record'
}
$item = #{
userUPN=$user.UserPrincipalName
userDisplayName = $user.DisplayName
lastLogin = $lastLogin
accountEnabled = $user.AccountEnabled
}
$results += New-Object PSObject -Property $item
}
$results | export-csv -Path d:\result.csv -NoTypeInformation
export to .csv file Result:
There is one thing that you should know, for different Azure AD service tier, the time that Azure AD keep these data is different, details see here.

Get all list in site without hidden list

I want to get all lists in site using sharepoint that without hidden list. Because i know that, when we list all lists, we will receive all including hidden list. Please help me, thank you very much
Try PnP PowerShell.
#region Variables
$Username = "user#tenant.onmicrosoft.com"
$Password = "password"
$siteURL = "https://tenant.sharepoint.com/sites/lee"
#endregion Variables
#region Credentials
[SecureString]$SecurePass = ConvertTo-SecureString $Password -AsPlainText -Force
[System.Management.Automation.PSCredential]$PSCredentials = New-Object System.Management.Automation.PSCredential($Username, $SecurePass)
#endregion Credentials
Connect-PnPOnline -Url $siteURL -Credentials $PSCredentials
$lists=Get-PnPList | ?{$_.Hidden -eq $false}
foreach($list in $lists){
Write-Host $list.Title +"Hidden:" $list.Hidden
}
write-host "done"

Resources