Forum Discussion

Test SharePoint's avatar
Test SharePoint
Brass Contributor
Oct 29, 2018
Solved

Powershell script fo deleting specific-files-from-sharepoint-on-premises-library error

I was going through article: http://romeodonca.com/deleting-specific-files-from-sharepoint-on-premises-library
I am getting an issue in implementing it. can you please have a look intothe following scenario:
 
 I tried the 1st script. it runs successfully however the files dont get deleted.
for eg:
my Site URL: http://contoso.com/subsitename
Library name: library
Filename: test
 
 
If you open my csv file, you will see the following list of URL's:
 
http://contoso.com/subsitename/library/New%20Text%20Document%20-%20Copy.txt
http://contoso.com/subsitename/library/New%20Text%20Document.txt
http://contoso.com/subsitename/library/New%20Text%20Document%20-%20Copy%20(2).txt
http://contoso.com/subsitename/library/New%20Text%20Document%20-%20Copy%20(3).txt
 
 
Please let me know whether I have to insert any column title in the csv or the above is just fine?
 
 
So My first script becomes:
 
param(
[Parameter(Mandatory=$true,HelpMessage=”http://contoso.com/subsitename”)][string]$SiteUrl,
[Parameter(Mandatory=$true,HelpMessage=”library”)][string]$LibraryName,
[Parameter(Mandatory=$true,HelpMessage=”test”)][string]$Filename
)
Add-PSSnapin microsoft.sharepoint.powershell
###################################### parse all items
function deleting($mylist,$yoursourcefile)
{
    $files = @()
    foreach ($searchedfile in (Import-Csv $yoursourcefile))
    {
        #$myweb = get-spweb (($searchedfile.url).split(‘/’)[0]+”//”+$searchedfile.url.split(‘/’)[2])
        #$mylist = $myweb.Lists | Where-Object {$_.Title -match ($searchedfile.url).split(‘/’)[3]}
        foreach ($file in $mylist.items)
        {
            if (($searchedfile.url) -eq (($searchedfile.url).split(‘/’)[0]+”//”+($searchedfile.url).split(‘/’)[2]+”/”+$file.url))
            {
                “Deleting: ” +  $searchedfile.url
                $files = $files + $file
                break
            }
        }
    }
    foreach ($item in $files)
    {
        $item.Delete()
    }
}
 
 
 
the above script runs however the files dont get deleted.
 
I am not sure What wrong.
I tried doing the CAML Query.
And I get the following errors with different inputs:
 
1)>>>>You cannot call a method on a null-valued expression.
At line:13 char:9
+         $file = $mylist.GetItems($query)
+         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull
 
 
2)>>>>>You cannot call a method on a null-valued expression.
At line:18 char:9
+         $item.Delete()
+         ~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull
 
 
 
3)>>>>>deleting : The term 'deleting' is not recognized as the name of a cmdlet,
function, script file, or operable program. Check the spelling of the name, or
if a path was included, verify that the path is correct and try again.
At line:39 char:21
+                     deleting $mylist $filename
+                     ~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (deleting:String) [], CommandNot
   FoundException
    + FullyQualifiedErrorId : CommandNotFoundException
 
 
4)>>>>Import-Csv : Cannot validate argument on parameter 'Path'. The argument is
null or empty. Provide an argument that is not null or empty, and then try the
command again.
At line:4 char:43
+     foreach ($searchedfile in (Import-Csv $test))
+                                           ~~~~
    + CategoryInfo          : InvalidData: (:) [Import-Csv], ParameterBindingV
   alidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.Power
   Shell.Commands.ImportCsvCommand
 
 
 
 
 
 
 
 
Can you please help me out in this. i am not sure what I am missing. How will the script turn out if I have the following inputs with me:
my Site URL: http://contoso.com/subsitename
Library name: library
Filename: test
 
 
csv file:
 
http://contoso.com/subsitename/library/New%20Text%20Document%20-%20Copy.txt
http://contoso.com/subsitename/library/New%20Text%20Document.txt
http://contoso.com/subsitename/library/New%20Text%20Document%20-%20Copy%20(2).txt
http://contoso.com/subsitename/library/New%20Text%20Document%20-%20Copy%20(3).txt
 
 
I would really appreciate help on this!! thanks again
  • Matt Weston's avatar
    Matt Weston
    Oct 30, 2018

    Hi Test SharePoint the way those errors are cascading, I think it's purely down to the entries that are coming from the CSV, and that all of the other errors are as a result of single issue. Do you have a header in your CSV? In mine, I had a header of File, so my CSV looked like this:

     

    File

    https://contoso.sharepoint.com/sites/SiteA/Documents/File1.docx

    https://contoso.sharepoint.com/sites/SiteA/Documents/File1 Copy.docx

4 Replies

  • Matt Weston's avatar
    Matt Weston
    Iron Contributor

    Hi Test SharePoint

     

    Most of the errors that you're encountering are caused by one part of your script failing, and therefore you have a number of null values being encountered.  To be honest you could probably simplify the script a lot

     

    # SET UP
    Add-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue

    CLS

    # PULL IN THE CSV
    $filelist = Import-Csv -Path "<PATH TO THE CSV>"



    foreach($file in $filelist)
    {
    Write-Host "Processing $($file.File)"

    # Figure out the URL of the site
    $arysiteurl = $file.File.Split('/')
    $url = ""
    for($x=0; $x -lt $arysiteurl.Length-2; $x++)
    {
    $url = $url + $arysiteurl[$x] + "/"
    }

    # Get the web
    $web = Get-SPWeb $url

    # Get the document based on the URL
    $file = $web.GetFile($file.File)
    $file.Delete()

    }
    • Test SharePoint's avatar
      Test SharePoint
      Brass Contributor

      thank you so much for your reply Matt Weston. looks simplified now.

       

      I ran the following script:

       

      # SET UP

      Add-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue

       

      CLS

       

      # PULL IN THE CSV

      $filelist = Import-Csv -Path "C:\temp"

       

       

       

      foreach($file in $filelist)

      {

       Write-Host "Processing $($file.File)"

       

      # Figure out the URL of the site

       $arysiteurl = $file.File.Split('/')

       $url = ""

       for($x=0; $x -lt $arysiteurl.Length-2; $x++)

       {

       $url = $url + $arysiteurl[$x] + "/"

       }

       

      # Get the web

       $web = Get-SPWeb $url

       

      # Get the document based on the URL

       $file = $web.GetFile($file.File)

       $file.Delete()

       

      }

       

      I get the following error:

      Processing
      You cannot call a method on a null-valued expression.
      At line:16 char:2
      + $arysiteurl = $file.File.Split('/')
      + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      + CategoryInfo : InvalidOperation: (:) [], RuntimeException
      + FullyQualifiedErrorId : InvokeMethodOnNull

      Get-SPWeb : Cannot find an SPSite object that contains the following Id or Url: Empty or Null.
      At line:24 char:9
      + $web = Get-SPWeb $url
      + ~~~~~~~~~~~~~~
      + CategoryInfo : InvalidData: (Microsoft.Share....SPCmdletGetWeb:SPCmdletGetWeb) [Get-SPWeb], SPCmdletPipeBindException
      + FullyQualifiedErrorId : Microsoft.SharePoint.PowerShell.SPCmdletGetWeb

      You cannot call a method on a null-valued expression.
      At line:27 char:2
      + $file = $web.GetFile($file.File)
      + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      + CategoryInfo : InvalidOperation: (:) [], RuntimeException
      + FullyQualifiedErrorId : InvokeMethodOnNull

      Method invocation failed because [System.Management.Automation.PSCustomObject] doesn't contain a method named 'Delete'.
      At line:28 char:2
      + $file.Delete()
      + ~~~~~~~~~~~~~~
      + CategoryInfo : InvalidOperation: (Delete:String) [], RuntimeException
      + FullyQualifiedErrorId : MethodNotFound

      Processing
      You cannot call a method on a null-valued expression.
      At line:16 char:2
      + $arysiteurl = $file.File.Split('/')
      + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      + CategoryInfo : InvalidOperation: (:) [], RuntimeException
      + FullyQualifiedErrorId : InvokeMethodOnNull

      Get-SPWeb : Cannot find an SPSite object that contains the following Id or Url: Empty or Null.
      At line:24 char:9
      + $web = Get-SPWeb $url
      + ~~~~~~~~~~~~~~
      + CategoryInfo : InvalidData: (Microsoft.Share....SPCmdletGetWeb:SPCmdletGetWeb) [Get-SPWeb], SPCmdletPipeBindException
      + FullyQualifiedErrorId : Microsoft.SharePoint.PowerShell.SPCmdletGetWeb

      You cannot call a method on a null-valued expression.
      At line:27 char:2
      + $file = $web.GetFile($file.File)
      + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      + CategoryInfo : InvalidOperation: (:) [], RuntimeException
      + FullyQualifiedErrorId : InvokeMethodOnNull

      Method invocation failed because [System.Management.Automation.PSCustomObject] doesn't contain a method named 'Delete'.
      At line:28 char:2
      + $file.Delete()
      + ~~~~~~~~~~~~~~
      + CategoryInfo : InvalidOperation: (Delete:String) [], RuntimeException
      + FullyQualifiedErrorId : MethodNotFound

      Processing
      You cannot call a method on a null-valued expression.
      At line:16 char:2
      + $arysiteurl = $file.File.Split('/')
      + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      + CategoryInfo : InvalidOperation: (:) [], RuntimeException
      + FullyQualifiedErrorId : InvokeMethodOnNull

      Get-SPWeb : Cannot find an SPSite object that contains the following Id or Url: Empty or Null.
      At line:24 char:9
      + $web = Get-SPWeb $url
      + ~~~~~~~~~~~~~~
      + CategoryInfo : InvalidData: (Microsoft.Share....SPCmdletGetWeb:SPCmdletGetWeb) [Get-SPWeb], SPCmdletPipeBindException
      + FullyQualifiedErrorId : Microsoft.SharePoint.PowerShell.SPCmdletGetWeb

      You cannot call a method on a null-valued expression.
      At line:27 char:2
      + $file = $web.GetFile($file.File)
      + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      + CategoryInfo : InvalidOperation: (:) [], RuntimeException
      + FullyQualifiedErrorId : InvokeMethodOnNull

      Method invocation failed because [System.Management.Automation.PSCustomObject] doesn't contain a method named 'Delete'.
      At line:28 char:2
      + $file.Delete()
      + ~~~~~~~~~~~~~~
      + CategoryInfo : InvalidOperation: (Delete:String) [], RuntimeException
      + FullyQualifiedErrorId : MethodNotFound

       

       

       

      I am not sure what I am missing. Can you please help me out on this one?

      My website URL: http:/contoso/subsitename

      My Document library name: test

      My csv file: sha.csv

       

      • Matt Weston's avatar
        Matt Weston
        Iron Contributor

        Hi Test SharePoint the way those errors are cascading, I think it's purely down to the entries that are coming from the CSV, and that all of the other errors are as a result of single issue. Do you have a header in your CSV? In mine, I had a header of File, so my CSV looked like this:

         

        File

        https://contoso.sharepoint.com/sites/SiteA/Documents/File1.docx

        https://contoso.sharepoint.com/sites/SiteA/Documents/File1 Copy.docx

Resources