Programmatically delete the contents of SharePoint 2013 recycle bin - powershell

Scenario:
Client would like a PowerShell script wrote to delete the 2nd stage recycle bin for a SharePoint 2013 Site Collection
Client's SharePoint requires a credential authorization on load.
Issue:
I have researched, however in regards to SharePoint 2013, I have yet to find a script example that involves using my credentials. However in the SharePoint Online examples for programmatically deleting a SP recycle bin they use credential authorization.
My attempts to splice these two scripts together have been met with no success.
Question: Would somone be able to assist me by taking a look at my code and letting me know where I am going wrong?
##Variables for Processing
$SiteUrl = "https://MySite/sites/site"
Try {
#Setup the context
$Context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteUrl)
$Context.Credentials = $Credentials
#Get the recycle bin
$Site = $Context.Site
$RecycleBinItems = $Site.RecycleBin
$Context.Load($Site)
$Context.Load($RecycleBinItems)
$Context.ExecuteQuery()
Write-Host "Total Number of Items found Recycle Bin:" $RecycleBinItems.Count
#sharepoint online powershell empty recycle bin
$RecycleBinItems.DeleteAll()
$Context.ExecuteQuery()
}
catch {
write-host "Error: $($_.Exception.Message)" -foregroundcolor Red
}

Related

PowerShell - Connect and disconnect from SPO

The script connects to SPO and read from excel. At the end I close the local excel instance and disconnect from SPO. Usually I am running the script so this is really necessary to do it every run? connect ad disconnect. Maybe there is another way to do it? ask if there is a valid active connection?
I saw that if the credentials are wrong for example the script is still reading from the sheet maybe from the memory, how can I protect from this scenario?
#Connecting to SharePoint Online site
Write-host "Connecting to SharePoint Online"
Connect-PnPOnline -Url $SharePointSiteURL # -Credentials $PSCredentials
$ExcelObject = New-Object -ComObject Excel.Application
$ExcelWorkBook = $ExcelObject.Workbooks.Open($SharePointSiteURL)
$ExcelWorkSheet = $ExcelWorkBook.Sheets.Item("VIP List")
function QuitExcel {
# when done, quit Excel and remove the used COM objects from memory (important)
$ExcelWorkBook.Close()
$ExcelObject.Quit()
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($ExcelWorkSheet)
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($ExcelWorkBook)
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($ExcelObject)
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
Disconnect-PnPOnline

Sharepoint online - MoveFile - pnp.powershell Status Updates

I'm trying to do folder/files moves from one sharepoint site to another, and I can't seem to get the Receive-PnPCopyMoveJobStatus to work in my powershell script
Right now the only way I can monitor a file/folder move is to monitor the source's recycling bin for changes. I'd like to be able to get progress either on demand, or consistently in an open powershell. Ideally I'd like to see a percentage sign, and even a verbose option.
Here's what I have put together:
#Config Variables
$SiteURL = "https://<site>.sharepoint.com/
$SourceFolderURL= "sites/<site name>/<document library name>/<Folder or file location>"
$TargetFolderURL = "sites/<site name>/<document library name>"
#Connect to PnP Online
Connect-PnPOnline -Url $SiteURL -interactive
#Sharepoint Copy/Move operation feedback
$Test = "Move-PnPFile -SourceUrl $SourceFolderURL -TargetUrl $TargetFolderURL -Overwrite -noWait"
$jobStatus = "Receive-PnPCopyMoveJobStatus -Job $Test"
if($jobStatus.JobState -eq 0)
{
Write-Host "Job finished"
}
referencing:
https://learn.microsoft.com/en-us/powershell/module/sharepoint-pnp/receive-pnpcopymovejobstatus?view=sharepoint-ps
I haven't been successful in running this. When I fill in the site names, library names, and actual site, I get a result that looks like it completes, but with no feedback, nor do the files move. So essentially nothing happens.
What does work for the file/folder move is the following:
#Config Variables
$SiteURL = "https://<site>.sharepoint.com/"
$SourceFolderURL= "sites/<site name>/<document library>/<folder name>"
$TargetFolderURL = "sites/<site name>/<document library>"
#Connect to PnP Online
Connect-PnPOnline -Url $SiteURL -interactive
#sharepoint online powershell move folder
Move-PnPFile -SourceUrl $SourceFolderURL -TargetUrl $TargetFolderURL -overwrite
#Read more: https://www.sharepointdiary.com/2017/06/how-to-move-folder-in-sharepoint-online.html#ixzz7Bkp822M1
Any help on correcting this script, or other methods on seeing the progress of Copy or Move operations on SharePoint would be appreciated!
The source url should be like "<document library>/<file name>"
Please try following script
$SiteURL = "https://<site>.sharepoint.com/sites/<sitesname>
$SourceFolderURL= "<document library name>/<file name>"
$TargetFolderURL = "<document library name>/<target file name>"
$job = Move-PnPFile -SiteRelativeUrl $SourceFolderURL -TargetUrl $TargetFolderURL -Overwrite
$jobStatus = Receive-PnPCopyMoveJobStatus -Job $result
if($jobStatus.JobState == 0)
{
Write-Host "Job finished"
}
Your non-working script contains:
$Test = "Move-PnPFile -SourceUrl $SourceFolderURL -TargetUrl $TargetFolderURL -Overwrite -noWait"
$jobStatus = "Receive-PnPCopyMoveJobStatus -Job $Test"
Both of these variable values are strings. They don't do anything except exist, and do not cause any commands to run. $jobStatus.JobState will always be null and never zero, because JobState is not a property of a string, so the if condition is never met.
If you want to run the commands, don't write them as strings inside double quotes, but just as they are in the documentation you referred to. You can actually run them, and capture their output, with e.g.
$jobStatus = Receive-PnPCopyMoveJobStatus -Job $Test
You can also just copy and paste the example and update the parameter values (though it seems to have the wrong variable name on the second line, which you've already fixed). You may have further errors once the commands are running, which should provide further diagnostic information. Make sure that you are doing all of connecting, requesting the move, and retrieving the status information in the same script.

Cannot open sharepoint UNC path unless already opened through Windows Explorer

I'm hoping somebody can shed light on this, because it has been driving me to distraction.
I have a script which will save the reports it creates to a sharepoint document library via UNC path, if the path exists, otherwise it saves to the UNC path of a network drive location as a fallback.
I've noticed that checking with test-path, saving (through an msexcel COM object) or trying to open the folder in windows explorer using invoke-item only work if I had already accessed the sharepoint site (via web browser or windows explorer) since the PC last logged on (I'm running Windows 7 Enterprise Service Pack 1 - 64-bit edition).
If I haven't yet been on to sharepoint manually since last logon, test-path returns false, and the other methods cause ItemNotFoundException e.g.
ii : Cannot find path '\\uk.sharepoint.mydomain.local\sites\mycompany\myteam\Shared Documents\Reports' because it does not exist.
At line:1 char:1
+ ii '\\uk.sharepoint.mydomain.local\sites\mycompany\myteam\Shared Document ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (\\uk.sharepoint...\Reports:String) [Invoke-Item], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.InvokeItemCommand
Example areas of code:
$LANPath = "\\myserver\myshare\teamdirs\scriptdir"
$SharepointPath = "\\uk.sharepoint.mydomain.local\sites\mycompany\myteam\Shared Documents\Reoprts"
$ScriptPath = $LANPath + "\bin"
If (Test-Path $SharepointPath) {$BasePath = $SharepointPath;write-host "Using sharepoint to save reports"} else {$BasePath = "$LANPath\Reports";write-host "Using LAN to save reports - sharepoint not accessible"}
and
$_|select -expandproperty HTMLBody | Out-File $($BasePath + "\Eml_body.html")
Write-Host "Reformating HTML"
$html = New-Object -ComObject "HTMLFile";
$source = Get-Content -Path ($BasePath + "\Eml_body.html") -Raw;
and when saving the excel spreadsheet from within my COM object:
$workbook._SaveAs($fileout,[Microsoft.Office.Interop.Excel.XlFileFormat]::xlOpenXMLWorkbook,$Missing,$Missing,$false,$false,[Microsoft.Office.Interop.Excel.XlSaveAsAccessMode]::xlNoChange,[Microsoft.Office.Interop.Excel.XlSaveConflictResolution]::xlLocalSessionChanges,$true,$Missing,$Missing)
You should be able to use a System.Net.WebClient object to access SharePoint file locations.
$client = New-Object System.Net.WebClient
The documentation for the WebClient.Credentials property suggests that the default credentials in this case may be for the ASP.NET server-side process rather than the current user's credentials:
If the WebClient class is being used in a middle tier application, such as an ASP.NET application, the DefaultCredentials belong to the account running the ASP page (the server-side credentials). Typically, you would set this property to the credentials of the client on whose behalf the request is made.
You therefore may want to set the credentials manually. You can plug them in as plain text...
$client.Credentials = New-Object System.Net.NetworkCredential("username","pswd","domain")
...or you could prompt the current user for their credentials.
$client.Credentials = Get-Credential
Here's an example that grabs a file and writes its content to the screen:
$client = New-Object System.Net.WebClient
$client.Credentials = Get-Credential
$data = $client.OpenRead("http://yoursharepointurl.com/library/document.txt")
$reader = New-Object System.IO.StreamReader($data)
$results = $reader.ReadToEnd()
Write-Host $results
$data.Close()
$reader.Close()
I know this is an old thread but for those searching, check out this link: https://www.myotherpcisacloud.com/post/Sometimes-I-Can-Access-the-WebDAV-Share-Sometimes-I-Cant!
Because SharePoint exposes its shares over WebDav, you need to ensure the WebClient service is running on the machine from which you are accessing the path. Browsing the path in explorer automatically fires up the service, while command-line methods do not.
If you change the startup type of WebClient to Automatic, it should resolve the issue.

Create folder with powershell in sharepoint (webservices)

I need to create a folder in sharepoint if it does not already exist. My powershell script is not running on the sharepoint server so I think I have to use the sharepoint web services? I am currently uploading files to sharepoint with powershell using webclient as below - but I need to create the folder for the file first... if it does not already exist;
# Upload the file
$webclient = New-Object System.Net.WebClient
$webclient.Credentials = $credentials
$webclient.UploadFile($destination + "/" + $File.Name, "PUT", $File.FullName)
Is this possible to do with webclient? If not, how can this be done using the sharepoint web services?
Since you mentioned SharePoint Web Services, Lists.UpdateListItems Method could be utilized for that purpose, for example:
Function Create-Folder([string]$WebUrl,[string]$ListUrl,[string]$ListName,[string]$FolderName)
{
$url = $WebUrl + "/_vti_bin/lists.asmx?WSDL"
$listsProxy = New-WebServiceProxy -Uri $url -UseDefaultCredential
$batch = [xml]"<Batch OnError='Continue' RootFolder='$WebUrl/$ListUrl'><Method ID='1' Cmd='New'><Field Name='ID'>New</Field><Field Name='FSObjType'>1</Field><Field Name='BaseName'>$FolderName</Field></Method></Batch>"
$result = $listsProxy.UpdateListItems($ListName, $batch)
}
Usages
Create Orders folder under Documents library:
Create-Folder -WebUrl "http://contoso.intranet.com" -ListUrl "Documents" -ListName "Documents" -FolderName "Orders"
Create 2014 folder in Requests list:
Create-Folder -WebUrl "http://contoso.intranet.com" -ListUrl "Lists/Requests" -ListName "Requests" -FolderName "2014"
Update
If folder already exists then SOAP service will throw the error:
The operation failed because an unexpected error occurred. (Result
Code: 0x8107090d)
but since OnError attribute is set to Continue for Batch Element, PowerShell will continue the execution.

Powershell Sharepoint snapin when not on the sharepoint server

I am new to both powershell and sharepoint, and I need to make script to automate the removal and uploading of attachments from outlook to sharepoint. I have easily completed the first part of extracting the attachment, however the uploading to sharepoint has become difficult do to my company's rules. As I understand to use sharepoint cmdlets you need to add the sharepoint snap-in but I am unable to do so because I dont have access to the sharepoint server. Is there anyway to the snapin without being on the server and if not can I upload it another way?
You can't add the SP snap in unless the server is a SP server. Instead, use a webservice/webclient approach to upload the file. Something like this should work depending on your SP version:
http://blog.sharepoint-voodoo.net/?p=205
Accepted answer link is broken.
This script uses PowerShell to upload a file to a document library in SharePoint using purely web service calls so it could be done remotely, also meaning it should work with O365 though I have not tried.
These variables are used throughout the script for source file, destination file and authentication. If your workstation is on the same domain as SharePoint, and your logged on user has permissions to the SharePoint site, you can omit $username, $password, and $domain
$LocalPath = "C:\filename.docx"
$spDocLibPath = "http://site.contoso.com/sites/spteam/Shared Documents/"
$username = "someone"
$password = "somepassword"
$domain = "contoso"
$UploadFullPath = $spDocLibPath + $(split-path -leaf $LocalPath)
$WebClient = new-object System.Net.WebClient
if($username -eq "" -or $password -eq "" -or $password -eq "")
{
# Use Local Logged on User Credentials
$WebClient.Credentials = [System.Net.CredentialCache]::DefaultCredentials
}
else
{
# Alternate Login for specifying credentials
$WebClient.Credentials = new-object System.Net.NetworkCredential($username, $password, $domain)
}
$WebClient.UploadFile($UploadFullPath, "PUT", $LocalPath)
https://web.archive.org/web/20160404174527/http://blog.sharepoint-voodoo.net/?p=205