0

I need to find out inactive users and replace them with active users as I am getting an error while copying the documents through PowerShell script due to author of the file no longer exists.

I know we can move or copy files using Moveto/Copyto option through UI.

I need this through PowerShell only.

Does anyone have an idea? Thanks for your help!!

0

Use the Sharegate tool, if you don't have a license you can use the trial version of the tool, there it is configurable, ie called missing user, you can map in the tool, if the user not found which user should be mapped.

However, if you need in PowerShell, you can refer to the below PowerShell script which will give you a report of all orphan users, so before the migration, you can replace these users with a valid user(you can have a dedicated migration user).

Orphan user details report in SharePoint Online

#Import SharePoint Online and Azure Online modules
Import-Module Microsoft.Online.SharePoint.Powershell
Import-Module MSOnline

Function Generate-OrphanedUsersReport ()
{
param
    (
        [Parameter(Mandatory=$true)] [string] $AdminURL,
        [Parameter(Mandatory=$true)] [string] $SiteURL,
        [Parameter(Mandatory=$true)] [string] $ReportOutput       
    )
Try {
    #Get Credentials to connect
    $Cred = Get-Credential

    #Connect to SharePoint and Azure AD
    Connect-MsolService -Credential $cred
    Connect-SPOService -Url $AdminURL -Credential $Cred

    #Function to check if a user account exists
    Function Check-UserExists()
    {
        Param( [Parameter(Mandatory=$true)] [string]$UserID )

        $User=Get-Msoluser -UserPrincipalName $UserID -Erroraction SilentlyContinue
        if ($User -ne $null)
        {
            Return $True
        }
        else
        {
            Return $false
        }
    }
    $OrphanedUsers = @()

    #Get all users of a given SharePoint Online site collection
    $AllUsers = Get-SPOUser $SiteURL -Limit ALL

    Foreach($User in $AllUsers)
    {
        #Exclude Built-in User Accounts and Security Groups
        if(($User.DisplayName.ToLower() -ne "nt authority\authenticated users") -and ($User.LoginName.ToLower() -ne "sharepoint\system") -and
        ($User.DisplayName.ToLower() -ne "sharepoint app") -and ($user.IsGroup -eq $false ) -and(-not $user.DisplayName.ToLower().Contains("_spocache")) -and
        (-not $user.DisplayName.ToLower().Contains("_spocrawl")) -and ($User.DisplayName.ToLower() -ne "sharepoint service administrator") -and
        ($User.DisplayName.ToLower() -ne "guest contributor") -and ($User.DisplayName.ToLower() -ne "everyone except external users")-and ($User.DisplayName.ToLower() -ne "company administrator"))
        {
            Write-host "Checking user $($user.DisplayName)" -f Yellow
            #Check if user exists
            if((Check-UserExists $User.LoginName) -eq $False)
            {
                Write-Host "User Doesn't Exists: $($user.DisplayName) - $($User.LoginName)" -f Red

                #Send the Result to CSV
                $Result = new-object PSObject
                $Result| add-member -membertype NoteProperty -name "LoginName" -Value $User.LoginName
                $Result | add-member -membertype NoteProperty -name "DisplayName" -Value $User.DisplayName
                $OrphanedUsers += $Result
            }
        }
    }
    #Export results to CSV
    $OrphanedUsers | Export-csv $ReportOutput -notypeinformation

        Write-host "Orphan Users Report Generated to $ReportOutput" -f Green
   }

    Catch {
    write-host -f Red "Error Deleting Unique Permissions!" $_.Exception.Message
    }
}

#Config Parameters
$AdminURL ="https://crescent-admin.sharepoint.com"
$SiteURL = "https://crescent.sharepoint.com"
$ReportOutput="C:\Temp\OrphanUsers.csv"

#Call the function to find and generate orphaned users report
Generate-OrphanedUsersReport -AdminURL $AdminURL -SiteURL $SiteURL -ReportOutput $ReportOutput

How to Delete Orphan Users from SharePoint Online with PowerShell:

#Import SharePoint Online module
Import-Module Microsoft.Online.SharePoint.Powershell

Function Remove-OrphanedUsers ()
{
param
    (
        [Parameter(Mandatory=$true)] [string] $AdminURL,
        [Parameter(Mandatory=$true)] [string] $SiteURL,
        [Parameter(Mandatory=$true)] [string] $ReportInput       
    )
    Try {
        #Get Credentials to connect
        $Cred = Get-Credential

        #Connect to SharePoint online
        Connect-SPOService -Url $AdminURL -Credential $Cred

        #Get the Data from CSV and Add to SharePoint List
        $OrphanUsers = Import-Csv $ReportInput
        Foreach ($Row in $OrphanUsers)
        {
            #Remove user from site
            Remove-SPOUser -Site $SiteURL -LoginName $Row.LoginName
            Write-host "Removed the Orphaned User $($Row.DisplayName) from $($SiteURL)"  
        }
            Write-host "Orphaned Users Removed from SharePoint Online Site!"
       }
    Catch {
    write-host -f Red "Error Deleting Orphan Users!" $_.Exception.Message
    }
}

#Config Parameters
$AdminURL ="https://crescent-admin.sharepoint.com"
$SiteURL = "https://crescent.sharepoint.com"
$ReportInput="C:\Temp\OrphanUsers.csv"

#Call the function to Remove Orphaned users
Remove-OrphanedUsers -AdminURL $AdminURL -SiteURL $SiteURL -ReportInput $ReportInput

Source:

SharePoint Online: Find and Delete Orphaned Users using PowerShell

0

I face issue when the author of the files no longer exist. To resolve this issue i've created power shell script to update the inactive author with active user.

Below is my script for this issue.

Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"

#Function to get all files of a folder
Function Get-FilesFromFolder([Microsoft.SharePoint.Client.Folder]$Folder)
{
    Write-host -f Yellow "Processing Folder:"$Folder.ServerRelativeUrl

    #Get All Files of the Folder
    $Ctx.load($Folder.files)
    $Ctx.ExecuteQuery()

    #list all files in Folder
    ForEach ($File in $Folder.files)
    {
        $Ctx.Load($File)
        $Ctx.Load($File.Author)
        $Ctx.Load($File.ModifiedBy)
        $Ctx.ExecuteQuery()

        if($File.Author.Title -eq $OrphanUserId)
        {
         #Get 'Created By' and 'Modified By' Users
         $Author = $Ctx.Web.EnsureUser($UserID)
         $Ctx.Load($Author)
         $Editor= $Ctx.Web.EnsureUser($UserID)
         $Ctx.Load($Editor)
         $Ctx.ExecuteQuery()
         #update Metadata of the File
         $ListItem = $File.ListItemAllFields
         $Listitem["Author"] = $Author
         $ListItem["Editor"] = $Editor
         $ListItem.Update()
         $Ctx.ExecuteQuery()
         Write-host -f Magenta "Updated Metadata for" $File.Name
        }
    }

    #Recursively Call the function to get files of all folders
    $Ctx.load($Folder.Folders)
    $Ctx.ExecuteQuery()

    #Exclude "Forms" system folder and iterate through each folder
    ForEach($SubFolder in $Folder.Folders | Where {$_.Name -ne "Forms"})
    {
        Get-FilesFromFolder -Folder $SubFolder
    }
}

#powershell list files in sharepoint online library
Function Get-SPODocLibraryFiles()
{
    param
    (
        [Parameter(Mandatory=$true)] [string] $SiteURL,
        [Parameter(Mandatory=$true)] [string] $LibraryName
    )
    Try {
        #Setup Credentials to connect
        $Cred = Get-Credential
        $Cred = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.UserName,$Cred.Password)

        #Setup the context
        $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
        $Ctx.Credentials = $Cred
        #Get the User
        $User = $Ctx.Web.EnsureUser($UserID)
        $ctx.Load($user)

        #Get the Library and Its Root Folder
        $Library=$Ctx.web.Lists.GetByTitle($LibraryName)
        $Ctx.Load($Library)
        $Ctx.Load($Library.RootFolder)
        $Ctx.ExecuteQuery()

        #Call the function to get Files of the Root Folder
        Get-FilesFromFolder -Folder $Library.RootFolder

     }
    Catch {
        write-host -f Red "Error Getting Files from Library!" $_.Exception.Message
    }
}
#Config Parameters
$SiteURL= Read-Host -Prompt 'Enter Site URL'
$LibraryName= Read-Host -Prompt 'Enter Library Name'
$OrphanUserId= Read-Host -Prompt 'Enter Inactive user display Name'
$UserID= Read-Host -Prompt 'Enter Replace User Mail ID'

#Call the function to Get All Files from a document library
Get-SPODocLibraryFiles -SiteURL $SiteURL -LibraryName $LibraryName

Source: https://www.sharepointdiary.com/2017/05/sharepoint-online-get-all-files-from-folder-using-powershell.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.