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.

11
  • 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, consultingblogs.emc.com/robertoortega/archive/2012/03/03/… Commented Nov 27, 2013 at 8: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 Commented Nov 27, 2013 at 9:28
  • Can you post the output when you try to run it? Commented Nov 27, 2013 at 9: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 Commented Nov 27, 2013 at 9:40
  • Can you edit your original question and copy and paste the script you are running exactly as it is in the .ps1 file. Commented Nov 27, 2013 at 9:42

4 Answers 4

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();
Sign up to request clarification or add additional context in comments.

2 Comments

This seems to require Sharepoint Snapin: 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 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.
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.

Comments

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

4 Comments

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
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
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.
I added a screenshot so that you can see what the formatting should look like.
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.