none
Not able to remove the SharePoint locations from a hold in an eDiscovery case in O365 security and compliance center using PowerShell scripting RRS feed

  • Question


  • I am in process of PowerShell automation of adding and removing the users and their respective SharePoint sites in an eDiscovery case hold in O365 security and Compliance center.

    I am able to add the users and respective SharePoint sites successfully to hold using the below script. 

    But i am not able to remove the users and respective SharePoint sites using the script and it is throwing the error that it"could not find the site in existing binding" 

    Script for adding the users and SharePoint sites

    #script begin

         

    " " 
    write-host "***********************************************"
    write-host "   Office 365 Security & Compliance Center   " -foregroundColor yellow -backgroundcolor darkgreen
    write-host "   eDiscovery cases - Add users to a hold   " -foregroundColor yellow -backgroundcolor darkgreen 
    write-host "***********************************************"
    " " 
    # Get user credentials & Connect to Office 365 SCC, SPO
    $CreateEXOPSSession = (Get-ChildItem -Path $env:userprofile -Filter CreateExoPSSession.ps1 -Recurse -ErrorAction SilentlyContinue -Force | Select -Last 1).DirectoryName; ."$CreateEXOPSSession\CreateExoPSSession.ps1"
    Connect-EXOPSSession
    $credentials = Get-Credential -Message "Specify your credentials to connect to the Office 365 Security & Compliance Center and SharePoint Online"
    $s = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri "https://ps.compliance.protection.outlook.com/powershell-liveid" -Credential $credentials -Authentication Basic -AllowRedirection -SessionOption (New-PSSessionOption -SkipCACheck -SkipCNCheck -SkipRevocationCheck)
    $a = Import-PSSession $s -AllowClobber
        if (!$s)
        {
            Write-Error "Couldn't create PowerShell session."
            return;
        }
    # Load the SharePoint assemblies from the SharePoint Online Management Shell
    # To install, go to http://go.microsoft.com/fwlink/p/?LinkId=255251
    if (!$SharePointClient -or !$SPRuntime -or !$SPUserProfile)
    {
        $SharePointClient = [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client")
        $SPRuntime = [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.Runtime")
        $SPUserProfile = [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.UserProfiles")
        if (!$SharePointClient)
        {
            Write-Error "The SharePoint Online Management Shell isn't installed. Please install it from: http://go.microsoft.com/fwlink/p/?LinkId=255251 and then re-run this script."
            return;
        }
    }
    if (!$spCreds)
    {
        $spCreds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($credentials.UserName, $credentials.Password)
    }
    # Get the user's MySite domain name. We use this to create the admin URL and root URL for OneDrive for Business
    ""
    $mySiteDomain = Read-Host "Enter the name of your organization's MySite domain. For example, 'contoso' for 'https://contoso-my.sharepoint.com'"
    ""
    # Get other required information
    do{
    $casename = Read-Host "Enter the name of the case"
    $caseexists = (get-compliancecase -identity "$casename" -erroraction SilentlyContinue).isvalid
    if($caseexists -ne 'True')
    {""
    write-host "A case named '$casename' doesn't exist. Please specify the name of an existing case, or create a new case and then re-run the script." -foregroundColor Yellow
    ""}
    }While($caseexists -ne 'True')
    ""
    do{
    $holdName = Read-Host "Enter the name of the hold"
    $holdexists=(get-caseholdpolicy -identity "$holdname" -case "$casename" -erroraction SilentlyContinue).isvalid
    if($holdexists -ne 'True')
    {""
    write-host "A hold named '$holdname' doesn't exists. Please specify the name of an existing hold, or create a new hold and then re-run the script." -foregroundColor Yellow
    ""}
    }While($holdexists -ne 'True')
    ""
    $holdQuery = Read-Host "Enter a search query to create a query-based hold, or press Enter to hold all content"
    ""
    $holdstatus = read-host "Do you want the hold enabled after it's created? (Yes/No)"
    do{
    ""
    $inputfile = read-host "Enter the name of the text file that contains the email addresses of the users to add to the hold"
    ""
    $fileexists = test-path -path $inputfile
    if($fileexists -ne 'True'){write-host "$inputfile doesn't exist. Please enter a valid file name." -foregroundcolor Yellow}
    }while($fileexists -ne 'True')
    #Import the list of addresses from the txt file.  Trim any excess spaces and make sure all addresses 
        #in the list are unique.
      [array]$emailAddresses = Get-Content $inputfile -ErrorAction SilentlyContinue | where {$_.trim() -ne ""}  | foreach{ $_.Trim() }
      [int]$dupl = $emailAddresses.count
      [array]$emailAddresses = $emailAddresses | select-object -unique
      $dupl -= $emailAddresses.count
    #Validate email addresses so the hold creation does not run in to an error.
    if($emailaddresses.count -gt 0){
    write-host ($emailAddresses).count "addresses were found in the text file. There were $dupl duplicate entries in the file." -foregroundColor Yellow
    ""
    Write-host "Validating the email addresses. Please wait..." -foregroundColor Yellow
    ""
    $finallist =@()
    foreach($emailAddress in $emailAddresses)
    {
    if((get-recipient $emailaddress -erroraction SilentlyContinue).isvalid -eq 'True')
    {$finallist += $emailaddress}
    else {"Unable to find the user $emailaddress"
    [array]$excludedlist += $emailaddress}
    }
    ""
    }
    #find user's OneDrive Site URL using email address
    Write-Host "Getting the URL for each user's OneDrive for Business site." -foregroundColor Yellow
    ""
    $mySiteDomain = "yaggu"
    $AdminUrl = "https://$mySiteDomain-admin.sharepoint.com"
    $mySiteUrlRoot = "https://$mySiteDomain-my.sharepoint.com"
    # Add the path of the User Profile Service to the SPO admin URL, then create a new webservice proxy to access it
    $proxyaddr = "$AdminUrl/_vti_bin/UserProfileService.asmx?wsdl"
    $UserProfileService= New-WebServiceProxy -Uri $proxyaddr -UseDefaultCredential False
    $UserProfileService.Credentials = $credentials
    # Take care of auth cookies
    $strAuthCookie = $spCreds.GetAuthenticationCookie($AdminUrl)
    $uri = New-Object System.Uri($AdminUrl)
    $container = New-Object System.Net.CookieContainer
    $container.SetCookies($uri, $strAuthCookie)
    $UserProfileService.CookieContainer = $container
    $urls = @()
    foreach($emailAddress in $emailAddresses)
    {
          try{
            $prop = $UserProfileService.GetUserProfileByName("i:0#.f|membership|$emailAddress") | Where-Object { $_.Name -eq "PersonalSpace" }
            $url = $prop.values[0].value
    if($url -ne $null){
            $furl = $mySiteUrlRoot + $url
            $urls += $furl
            Write-Host "- $emailAddress => $furl"
    [array]$ODadded += $furl}
      else{    
            Write-Warning "Couldn't locate OneDrive for $emailAddress"
    [array]$ODExluded += $emailAddress
        }}
      catch { 
      Write-Warning "Could not locate OneDrive for $emailAddress"
      [array]$ODExluded += $emailAddress
      Continue }
    }
    if(($finallist.count -gt 0) -or ($urls.count -gt 0)){
    ""
    Write-Host "Adding users to the hold named $holdname. Please wait..." -foregroundColor Yellow
    if(($holdstatus -eq "Y") -or ($holdstatus -eq  "y") -or ($holdstatus -eq "yes") -or ($holdstatus -eq "YES")){
    set-CaseHoldPolicy -Identity "$holdName" -AddExchangeLocation $finallist -AddSharePointLocation $urls -Enabled $True | out-null
    set-CaseHoldRule -Identity "$holdName" -ContentMatchQuery $holdQuery -Disabled $false| out-null
    }
    else{
    set-CaseHoldPolicy -Identity "$holdName" -AddExchangeLocation $finallist -AddSharePointLocation $urls -Enabled $false | out-null
    set-CaseHoldRule -Identity "$holdName" -ContentMatchQuery $holdQuery -disabled $true | out-null
    }
    ""

    }
    else {"No valid locations were identified. Therefore, the hold wasn't created."}

    Script for removing the users and SharePoint sites:

         

    #script begin
    " " 
    write-host "***********************************************"
    write-host "   Office 365 Security & Compliance Center   " -foregroundColor yellow -backgroundcolor darkgreen
    write-host "   eDiscovery cases - Add users to a hold   " -foregroundColor yellow -backgroundcolor darkgreen 
    write-host "***********************************************"
    " " 
    # Get user credentials & Connect to Office 365 SCC, SPO
    $CreateEXOPSSession = (Get-ChildItem -Path $env:userprofile -Filter CreateExoPSSession.ps1 -Recurse -ErrorAction SilentlyContinue -Force | Select -Last 1).DirectoryName; ."$CreateEXOPSSession\CreateExoPSSession.ps1"
    Connect-EXOPSSession
    $credentials = Get-Credential -Message "Specify your credentials to connect to the Office 365 Security & Compliance Center and SharePoint Online"
    $s = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri "https://ps.compliance.protection.outlook.com/powershell-liveid" -Credential $credentials -Authentication Basic -AllowRedirection -SessionOption (New-PSSessionOption -SkipCACheck -SkipCNCheck -SkipRevocationCheck)
    $a = Import-PSSession $s -AllowClobber
        if (!$s)
        {
            Write-Error "Couldn't create PowerShell session."
            return;
        }
    # Load the SharePoint assemblies from the SharePoint Online Management Shell
    # To install, go to http://go.microsoft.com/fwlink/p/?LinkId=255251
    if (!$SharePointClient -or !$SPRuntime -or !$SPUserProfile)
    {
        $SharePointClient = [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client")
        $SPRuntime = [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.Runtime")
        $SPUserProfile = [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.UserProfiles")
        if (!$SharePointClient)
        {
            Write-Error "The SharePoint Online Management Shell isn't installed. Please install it from: http://go.microsoft.com/fwlink/p/?LinkId=255251 and then re-run this script."
            return;
        }
    }
    if (!$spCreds)
    {
        $spCreds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($credentials.UserName, $credentials.Password)
    }
    # Get the user's MySite domain name. We use this to create the admin URL and root URL for OneDrive for Business
    ""
    $mySiteDomain = Read-Host "Enter the name of your organization's MySite domain. For example, 'contoso' for 'https://contoso-my.sharepoint.com'"
    ""
    # Get other required information
    do{
    $casename = Read-Host "Enter the name of the case"
    $caseexists = (get-compliancecase -identity "$casename" -erroraction SilentlyContinue).isvalid
    if($caseexists -ne 'True')
    {""
    write-host "A case named '$casename' doesn't exist. Please specify the name of an existing case, or create a new case and then re-run the script." -foregroundColor Yellow
    ""}
    }While($caseexists -ne 'True')
    ""
    do{
    $holdName = Read-Host "Enter the name of the hold"
    $holdexists=(get-caseholdpolicy -identity "$holdname" -case "$casename" -erroraction SilentlyContinue).isvalid
    if($holdexists -ne 'True')
    {""
    write-host "A hold named '$holdname' doesn't exists. Please specify the name of an existing hold, or create a new hold and then re-run the script." -foregroundColor Yellow
    ""}
    }While($holdexists -ne 'True')
    ""
    $holdQuery = Read-Host "Enter a search query to create a query-based hold, or press Enter to hold all content"
    ""
    $holdstatus = read-host "Do you want the hold enabled after it's created? (Yes/No)"
    do{
    ""
    $inputfile = read-host "Enter the name of the text file that contains the email addresses of the users to add to the hold"
    ""
    $fileexists = test-path -path $inputfile
    if($fileexists -ne 'True'){write-host "$inputfile doesn't exist. Please enter a valid file name." -foregroundcolor Yellow}
    }while($fileexists -ne 'True')
    #Import the list of addresses from the txt file.  Trim any excess spaces and make sure all addresses 
        #in the list are unique.
      [array]$emailAddresses = Get-Content $inputfile -ErrorAction SilentlyContinue | where {$_.trim() -ne ""}  | foreach{ $_.Trim() }
      [int]$dupl = $emailAddresses.count
      [array]$emailAddresses = $emailAddresses | select-object -unique
      $dupl -= $emailAddresses.count
    #Validate email addresses so the hold creation does not run in to an error.
    if($emailaddresses.count -gt 0){
    write-host ($emailAddresses).count "addresses were found in the text file. There were $dupl duplicate entries in the file." -foregroundColor Yellow
    ""
    Write-host "Validating the email addresses. Please wait..." -foregroundColor Yellow
    ""
    $finallist =@()
    foreach($emailAddress in $emailAddresses)
    {
    if((get-recipient $emailaddress -erroraction SilentlyContinue).isvalid -eq 'True')
    {$finallist += $emailaddress}
    else {"Unable to find the user $emailaddress"
    [array]$excludedlist += $emailaddress}
    }
    ""
    }
    #find user's OneDrive Site URL using email address
    Write-Host "Getting the URL for each user's OneDrive for Business site." -foregroundColor Yellow
    ""
    $mySiteDomain = "yaggu"
    $AdminUrl = "https://$mySiteDomain-admin.sharepoint.com"
    $mySiteUrlRoot = "https://$mySiteDomain-my.sharepoint.com"
    # Add the path of the User Profile Service to the SPO admin URL, then create a new webservice proxy to access it
    $proxyaddr = "$AdminUrl/_vti_bin/UserProfileService.asmx?wsdl"
    $UserProfileService= New-WebServiceProxy -Uri $proxyaddr -UseDefaultCredential False
    $UserProfileService.Credentials = $credentials
    # Take care of auth cookies
    $strAuthCookie = $spCreds.GetAuthenticationCookie($AdminUrl)
    $uri = New-Object System.Uri($AdminUrl)
    $container = New-Object System.Net.CookieContainer
    $container.SetCookies($uri, $strAuthCookie)
    $UserProfileService.CookieContainer = $container
    $urls = @()
    foreach($emailAddress in $emailAddresses)
    {
          try{
            $prop = $UserProfileService.GetUserProfileByName("i:0#.f|membership|$emailAddress") | Where-Object { $_.Name -eq "PersonalSpace" }
            $url = $prop.values[0].value
    if($url -ne $null){
            $furl = $mySiteUrlRoot + $url
            $urls += $furl
            Write-Host "- $emailAddress => $furl"
    [array]$ODadded += $furl}
      else{    
            Write-Warning "Couldn't locate OneDrive for $emailAddress"
    [array]$ODExluded += $emailAddress
        }}
      catch { 
      Write-Warning "Could not locate OneDrive for $emailAddress"
      [array]$ODExluded += $emailAddress
      Continue }
    }
    if(($finallist.count -gt 0) -or ($urls.count -gt 0)){
    ""
    Write-Host "Removing users from the hold named $holdname. Please wait..." -foregroundColor Yellow
    if(($holdstatus -eq "Y") -or ($holdstatus -eq  "y") -or ($holdstatus -eq "yes") -or ($holdstatus -eq "YES")){
    #set-CaseHoldPolicy -Name "$holdName" -Case "$casename" -ExchangeLocation $finallist -SharePointLocation $urls -Enabled $True | out-null
    set-CaseHoldPolicy -Identity "$holdName" -RemoveExchangeLocation $finallist -RemoveSharePointLocation $urls -Enabled $True | out-null
    #set-CaseHoldPolicy -Identity "$holdName" -RemoveSharePointLocation $urls -RemoveExchangeLocation $finallist -Enabled $True | out-null
    #set-CaseHoldRule -Name "$holdName" -Policy "$holdname" -ContentMatchQuery $holdQuery -Disabled $false| out-null
    set-CaseHoldRule -Identity "$holdName" -ContentMatchQuery $holdQuery -Disabled $false| out-null
    }
    else{
    #set-CaseHoldPolicy -Name "$holdName" -Case "$casename" -ExchangeLocation $finallist -SharePointLocation $urls -Enabled $false | out-null
    #set-CaseHoldRule -Name "$holdName" -Policy "$holdname" -ContentMatchQuery $holdQuery -disabled $true | out-null

    set-CaseHoldPolicy -Identity "$holdName" -RemoveExchangeLocation $finallist -RemoveSharePointLocation $urls -Enabled $false | out-null
    #set-CaseHoldPolicy -Identity "$holdName" -RemoveSharePointLocation $urls -RemoveExchangeLocation $finallist -Enabled $false | out-null
    set-CaseHoldRule -Identity "$holdName" -ContentMatchQuery $holdQuery -disabled $true | out-null
    }
    ""

    }
    else {"No valid locations were identified. Therefore, the hold wasn't created."}

    Attached the error screenshot. 

    Could someone help me for finding what is causing the issue.


    Regards,

    Jagadeesh


    • Moved by Bill_Stewart Wednesday, September 4, 2019 6:41 PM This is not "train me in command usage" forum
    Friday, March 15, 2019 8:06 AM

All replies

  • Sorry but we do not fix or modify scripts you have found on the Internet.  Please contact the author of the script for help.


    \_(ツ)_/

    Friday, March 15, 2019 2:31 PM
  • Hi,

    I took reference from the below Microsoft doc and customized the script as per the requirements.

    https://docs.microsoft.com/en-us/office365/securitycompliance/use-a-script-to-add-users-to-a-hold-in-ediscovery 

    And it is working fine for adding users and SharePoint sites to Hold but getting issue while removing the SharePoint sites alone and able to remove the users as well. Could you help me at which scenarios the below error will be occurring which will help me for fixing the issue.

    Errror message

    Removing users from the hold named testhold2. Please wait...
    Could not find the site 'https://yaggu-my.sharepoint.com/personal/jagadeesh_yaggu_onmicrosoft_com/' in the existing binding.
        + CategoryInfo          : NotSpecified: (:) [Set-CaseHoldPolicy], ErrorFindSPSiteException
        + FullyQualifiedErrorId : [Server=MA1IND01WS012,RequestId=197672a1-9a55-41df-8c0a-a4b455d9f813,TimeStamp=3/17/2019 1:28:46 PM] [ 
       FailureCategory=Cmdlet-ErrorFindSPSiteException] 5F1D1035,Microsoft.Office.CompliancePolicy.Tasks.SetCaseHoldPolicy
        + PSComputerName        : ind01b.ps.compliance.protection.outlook.com

    Sunday, March 17, 2019 1:29 PM
  • You parameters are wrong.  Post in the SharePoint forum to learn how to select the correct parameters.


    \_(ツ)_/

    Sunday, March 17, 2019 2:50 PM
  • Thanks . will do
    Sunday, March 17, 2019 3:54 PM
  • Could you let me know which parameters are wrong
    Monday, March 18, 2019 7:54 AM