5

I want to upload the same file to multiple site collections with the same hierarchy in all the site collections. I want to use PowerShell and include auto check-in/check-out functionality.

I have able to upload the file in SharePoint. Below is the code. :

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint") > $null

# create the Variable Path and Pass the source folder path
$path = “D:\ABC\DEF\26Nov\”;

# create the Variable destination and pass the URL of the SharePoint List
$destination = "complete URL of File will be mentioned here";

# Store the current user default credentials in the Variable Credentials
$credentials = [System.Net.CredentialCache]::DefaultCredentials;

# Create the object of the Webclient
$webclient = New-Object System.Net.WebClient;

# Pass the user credentials
$webclient.Credentials = $credentials; Get-ChildItem

# “For Each” loop will upload all of the files one by one onto the destination using the UploadFile method
Get-ChildItem $path | ForEach-Object { $webclient.UploadFile($destination + “/” + $_.Name, “PUT”, $_.FullName)};

By this code the file is uploaded but checked out. I want it to be checked in automatically. In case the file is there then first automatically check-out and then check in.

TylerH
  • 20,799
  • 66
  • 75
  • 101
Kishan
  • 117
  • 1
  • 3
  • 16
  • I'm not going to put this as an answer since I'm just copying from another post. This will probably get you on the way, http://consultingblogs.emc.com/robertoortega/archive/2012/03/03/checking-in-all-files-in-a-document-library-from-powershell.aspx – Ola Ekdahl Nov 27 '13 at 08:36
  • Thanks Ola, I have checked out this code but I am not able to understand , how should I use the two code together. Calling this code after upload code doesn't work. Thanks – Kishan Nov 27 '13 at 09:28
  • Can you post the output when you try to run it? – Ola Ekdahl Nov 27 '13 at 09:38
  • the window suddenly Disappears. I am using the above code it only upload the file but not work for checkin/checkout. So can we use any function to get this. !! Much Thanks for your suport – Kishan Nov 27 '13 at 09:40
  • Can you edit your original question and copy and paste the script you are running exactly as it is in the .ps1 file. – Ola Ekdahl Nov 27 '13 at 09:42
  • I have edited it – Kishan Nov 27 '13 at 09:47
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/42024/discussion-between-kishan-and-ola-ekdahl) – Kishan Nov 27 '13 at 09:51
  • Much thanks for your this code it is giving me the error thanks unable to find the dll.Error :- new-Object : Cannot find type [Microsoft.SharePoint.SPSite]: make sure the assembly containing this type is loaded. At D:\Development\Manila Automation\PowerShell\checkin.ps1:4 char:12 + return new-Object Microsoft.SharePoint.SPSite($url) Just for your Info No SharePoint install in this system, I am working from a Client perspective...!! – Kishan Nov 27 '13 at 14:14
  • Aha, that explains a few things. Can you use PowerShell remoting to do this? Good walk through here, http://blogs.msdn.com/b/opal/archive/2010/03/07/sharepoint-2010-with-windows-powershell-remoting-step-by-step.aspx. Also, does it have to be done using PowerShell? You could also use the .NET client-side object model and write a client side .NET app. – Ola Ekdahl Nov 27 '13 at 14:24
  • Error : PS C:\> Enable-PSRemoting Do you want to continue? y WinRM is already set up to receive requests on this computer. Set-WSManQuickConfig : path="%systemroot%\system32\WsmSvc.dll"> firewall exception will not work since one of the network connection types on this machine is set to Public. Change the network connection type to either Domain or Private and try again This is the error I am getting @Ola... seriously I am pissed off, But seriously thanks, Now I am trying client object. – Kishan Nov 28 '13 at 08:25
  • You'll figure it out eventually :). This is s good start for using CSOM, http://blogs.msdn.com/b/sridhara/archive/2010/03/12/uploading-files-using-client-object-model-in-sharepoint-2010.aspx – Ola Ekdahl Nov 28 '13 at 08:34

4 Answers4

8

Here is simple script in layman style which is tested and working fine to upload files from your drive to SharePoint document library

http://soreddymanjunath.blogspot.in/2014/07/add-file-to-document-library-using.html

cls

asnp "*sh*"

$url=Read-Host "Enter Site Url" 

$web=Get-SPWeb -Identity $url

if($web)
{
try
{
$list = $web.Lists.TryGetList("Documents")

$files = Get-ChildItem -Path "D:\Manju" -Force -Recurse

    foreach ($file in $files)
    {
      $stream = $file.OpenRead()

      $done= $list.RootFolder.Files.Add($file.Name, $stream, $true)

      Write-Host $done.Name  "Uploaded into the Site" -BackgroundColor Green         

    }
}
catch
{
$ErrorMessage = $_.Exception.Message
Write-Host $ErrorMessage
}
}

else
{
Write-Host "Site Doesn't exist"
}

$list.Update();
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • This seems to require [Sharepoint Snapin](https://stackoverflow.com/q/11122585/7032856): `Get-SPWeb : The term 'Get-SPWeb' 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.` – Nae Oct 15 '18 at 13:43
  • 1
    @Nae Any work with SharePoint in PowerShell will require either the SP or PnP modules be installed first. That's true for any application-specific PS script. – TylerH Mar 20 '20 at 06:34
0

I ran this script successfully on my server. It uploads all documents from C:\Users\student\Documents\My Documents with a docx file extension to a document library called Upload Demo. After upload it checks in all the documents in that library.

I used scripts from these two references:

.

Add-PSSnapin Microsoft.SharePoint.PowerShell 
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint") > $null
$spWeb = Get-SPWeb -Identity "http://mia-sqlbi.adventureworks.msft/"
$spFolder = $spWeb.GetFolder("Upload Demo")
$spFileCollection = $spFolder.Files 

Get-ChildItem "C:\Users\student\Documents\My Documents" -filter ?*.docx? | ForEach {
    $spFileCollection.Add("Upload Demo/$($_.Name)",$_.OpenRead(),$true) 
} 

function global:Get-SPSite($url) {
    return new-Object Microsoft.SharePoint.SPSite($url)
}

$siteColletion = Get-SPSite("http://mia-sqlbi.adventureworks.msft/");

$folder = $siteColletion.RootWeb.Folders["Upload Demo"];

$collFiles = $folder.Files;

for ($intIndex=0; $intIndex -ne $folder.Count; $intIndex++) {
    if ($folder[$intIndex].CheckedOutBy.LoginName -eq "adventureworks\student") {
      $folder[$intIndex].CheckIn("");
   }
}

$siteColletion.Dispose()

Here's a screen shot of what it should look like:

enter image description here

David Clarke
  • 12,888
  • 9
  • 86
  • 116
Ola Ekdahl
  • 1,484
  • 1
  • 11
  • 21
  • The code block formatting doesn't work for some reason on the PowerShell script. It start here --> Add-PSSnapin Microsoft.SharePoint.PowerShell [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint") > $null – Ola Ekdahl Nov 27 '13 at 10:22
  • Thanks @Ola Above I have posted the script I am using. its still throwing some error : char:96 + ... COM/$($.Name)",$.OpenRead(),$true) } + ~ Missing expression after ','. At D:\Development\Manila Automation\PowerShell\UploadOla.ps1:5 char:96 + ... COM/$($.Name)",$.OpenRead(),$true) } Can you please tell me what is the error in my code I am using Much Thanks for your support – Kishan Nov 27 '13 at 10:43
  • My guess is that the formatting is off from copying and pasting the code. Use ISE and it will help you and make sure the formatting is correct. – Ola Ekdahl Nov 27 '13 at 11:11
  • I added a screenshot so that you can see what the formatting should look like. – Ola Ekdahl Nov 27 '13 at 11:34
0

Thank you so much for the response, I tried to do the same way you suggested.

Add-PSSnapin Microsoft.SharePoint.PowerShell     

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint") > $null

$spWeb = Get-SPWeb -Identity "//abc/enterprise/en-sg/RenderingAssets/" $spFolder =  $spWeb.GetFolder("oneMSCOM") $spFileCollection = $spFolder.Files 

Get-ChildItem "D:\test" -filter ?*.txt? | ForEach {
    $spFileCollection.Add("oneMSCOM/$($.Name)",$.OpenRead(),$true) 
}

function global:Get-SPSite($url){ 
    return new-Object Microsoft.SharePoint.SPSite($url) 
}

$siteColletion = Get-SPSite("://abc/enterprise/en-sg/RenderingAssets/");

$folder = $siteColletion.RootWeb.Folders["Upload Demo"];

$collFiles = $folder.Files;

for ($intIndex=0; $intIndex -ne $folder.Count; $intIndex++) { 
    if ($folder[$intIndex].CheckedOutBy.LoginName -eq "FAREAST\v-kisriv") { 
        $folder[$intIndex].CheckIn(""); 
    }
}

$siteColletion.Dispose()

In this the complete URL where file should be upload is :

://abc/enterprise/en-sg/RenderingAssets/oneMSCOM/

RenderingAssets : Document Libray
OneMSCOM : folder.
Community
  • 1
  • 1
Kishan
  • 117
  • 1
  • 3
  • 16
0
Add-PSSnapin microsoft.sharepoint.powershell
$web = Get-SPWeb "http://dc01:9876"
$lst = $web.Lists.TryGetList("Style Library")
$DirLoc = "C:\Work\Style Library\20April2015"

$relativeUrl = $lst.RootFolder.ServerRelativeUrl;

function UploadToLibrary($spurl,$filepath){
    Get-ChildItem -path $filepath -Directory |ForEach-Object {
        $FldrName=($spurl,$_.Name -join "/")
        $CheckFolder= $web.GetFolder($FldrName)
        if(-not $CheckFolder.Exists)
        {
            $tmp=$web.GetFolder($spurl).SubFolders.Add($FldrName);
        }
        UploadToLibrary ($spurl,$_.Name -join "/") ($filepath,$_.Name -join "\") 
    }
    $FilesToAdd=$web.GetFolder($spurl)
    Get-ChildItem -path $filepath -File |ForEach-Object {
        $_.FullName
        $bytes = [System.IO.File]::ReadAllBytes($_.FullName)
        $x=$FilesToAdd.Files.Add($_.Name,$bytes,$true);
    }
}

UploadToLibrary $relativeUrl $DirLoc
George
  • 2,842
  • 2
  • 15
  • 11