Created
December 14, 2016 16:11
-
-
Save anonymous/0fd2dec277f644b88435348e79f70b98 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#SharePoint 2010 Multiple File Upload Script by Phil Childs | |
#For more information and scripts, visit http://get-spscripts.com | |
#Follow me on Twitter at http://twitter.com/PhillipChilds | |
# | |
# 2016-10-04 - KMT01 - Modified to remove the Manifest file processing to simplify the script | |
# Added Check-IllegalCharacters | |
# | |
# Instructions. Run this script and see the text "SharePoint 2010 Multiple File Upload Script - Get-SPScripts.com" | |
# At the command prompt run a command such as this: | |
# | |
# Copy-FilestoSP -LocalPath “P:\Local_KC\CM Shared" -LocalFilter "*signed*.*" -SiteUrl "http://mygateway.miq.com/libraries/CarrierServices" -Library "Documents" -LibraryStartFolder “/CM Shared” -IncludeSubFolders | |
# | |
# Copy-FilestoSP -LocalPath “\\transportation.com\Public\Local_KC\CM Shared\*signed*.*" -SiteUrl "http://mygateway.miq.com/libraries/CarrierServices" -Library "Documents" -LibraryStartFolder “/CM Shared” -IncludeSubFolders -Approve -CheckIn | |
# | |
$scriptpath = split-path $SCRIPT:MyInvocation.MyCommand.Path -parent | |
if((Get-PSSnapin "Microsoft.SharePoint.PowerShell") -eq $null) | |
{ | |
Add-PSSnapin Microsoft.SharePoint.PowerShell | |
} | |
function Copy-FilestoSP | |
{ | |
Param ( | |
[parameter(Mandatory=$true)][string]$LocalPath, | |
[parameter(Mandatory=$true)][string]$LocalFilter, | |
[parameter(Mandatory=$true)][string]$SiteUrl, | |
[parameter(Mandatory=$true)][string]$Library, | |
[parameter(Mandatory=$false)][string]$LibraryStartFolder, | |
[parameter(Mandatory=$false)][switch]$IncludeSubFolders, | |
[parameter(Mandatory=$false)][switch]$Approve, | |
[parameter(Mandatory=$false)][switch]$CheckIn, | |
[parameter(Mandatory=$false)][switch]$Overwrite, | |
[parameter(Mandatory=$false)][switch]$FlattenStructure | |
) | |
$CCimport = @() | |
$CCimport = Import-Csv $scriptpath\CC_Export_12_2_2016.csv | |
$sqltext = $null | |
$SqlText = "INSERT INTO Claim_Document(claim_id,document_id,document_title,created_date,created_by)" | |
$OktoDelete = @() | |
try | |
{ | |
#Get web and document library objects | |
$web = Get-SPWeb $SiteUrl | |
$docLibrary = $web.Lists[$Library] | |
#Check for the LibraryStartFolder parameter to specify a root folder | |
if ($PSBoundParameters.ContainsKey('LibraryStartFolder')) { | |
$folder = $web.GetFolder($docLibrary.Title + $LibraryStartFolder) | |
} | |
else | |
{ | |
$folder = $docLibrary.RootFolder | |
} | |
# | |
# Attach to local folder and enumerate through all files | |
# | |
$LocalPathFilter = $LocalPath + "\" + $LocalFilter | |
write-host "Enumerating local files matching" $LocalPathFilter | |
if($IncludeSubFolders) { | |
$files = Get-ChildItem $LocalPathFilter -Exclude "~*.*" -Recurse | |
} | |
else | |
{ | |
$files = Get-ChildItem $LocalPathFilter -Exclude "~*.*" | |
} | |
write-host "Found" $files.Length "local files matching" $LocalPathFilter | |
# | |
# Iterate over matched files | |
# | |
$files | ForEach-Object { | |
try { | |
$RelFolder = $folder | |
$RelSPPath = "" | |
if (($IncludeSubFolders) -and (!$FlattenStructure)) { | |
# | |
# Preserve the file structure so break-up relative folders and check each one exists or create | |
# | |
$RelPath = $_.DirectoryName.Substring($LocalPath.Length + 1) # Add 1 for the beginning slash | |
$PathParts = $RelPath.split("\"); | |
$RelSPPath = "" | |
$PathParts | ForEach-Object { | |
# | |
# Check this relative folder | |
# | |
$PathPart = $_ | |
$PathPart = Fix-IllegalCharacters $PathPart | |
if($_ -ne $PathPart) { | |
Write-Host $_ "renamed to" $PathPart -ForegroundColor Yellow | |
} | |
if ($PathPart.Length -gt 127) | |
{ | |
Write-Host $PathPart is 128 characters or over and will need to be truncated -ForegroundColor Red | |
} else { | |
# | |
# Check Folder Exists | |
# | |
$RelSPPath = $RelSPPath + "/" + $PathPart | |
$TestFolder = $RelFolder.SubFolders[$PathPart] | |
if ($TestFolder -eq $null) { | |
# | |
# Create Relative folder | |
# | |
write-host "Creating Folder" $RelSPPath -foregroundcolor Cyan | |
try { | |
$RelFolder = $RelFolder.SubFolders.Add($PathPart) | |
} catch [System.SystemException] { | |
write-host "Error creating folder: "$_.Message | |
} | |
} else { | |
$RelFolder = $TestFolder | |
} | |
} | |
} | |
} | |
# | |
# Handle the File upload | |
# | |
#[string]$Leaf = [System.IO.Path]::GetFileNameWithoutExtension($_.Name) | |
[string]$Leaf = split-path $_.name -leaf | |
$SPFilename = $_.Name | |
$SPFilename = Fix-IllegalCharacters $SPFilename | |
if(!($Leaf -match "B12[0-9][0-9][0-9][0-9]")) { | |
$SPFileName -match "B12[0-9][0-9][0-9][0-9]" | |
$SPFilename = $SPFilename.TrimEnd($leaf) | |
$Leaf = $Matches.Values + $Leaf | |
$SPFilename = $SPFilename + $Leaf | |
} | |
if($_.Name -ne $SPFilename) { | |
Write-Host $_.Name "renamed to" $SPFilename -ForegroundColor Yellow | |
} | |
$SPFileName -match "B12[0-9][0-9][0-9][0-9]" | |
$filepathmatch = $Matches.Values | |
$ccid=$null | |
foreach ($cc in $CCImport) { | |
if($cc.claim_number -eq $filepathmatch) { | |
$ccnum = $cc.claim_number | |
$cctype = $cc.claim_type_description | |
$ccfbpn = $cc.freight_bill_pro_number | |
$ccid = $cc.claim_id | |
break | |
} | |
<# elseif (!$cctype) { | |
[string]$ccnum=$filepathmatch | |
if(!$cctype) { | |
$cctype=" " | |
$ccfpbn=" " | |
$ccid=$null | |
} | |
} | |
else { | |
$ccobject=$null | |
}#> | |
} | |
if ($ccid -ne $null){ | |
if ($PathPart.Length -gt 127) | |
{ | |
Write-Host $PathPart is 128 characters or over and will need to be truncated -ForegroundColor Red | |
} else { | |
# | |
# Calculate paths and see if file exists or not at destination location in SP | |
# | |
$DestSPFile = $SiteUrl + "/" + $Library + $LibraryStartFolder + $RelSPPath + "/" + $SPFileName | |
$DestSPPath = $SiteUrl + "/" + $Library + $LibraryStartFolder + $RelSPPath | |
if ((!$web.GetFile($DestSPFile).Exists) -or ($Overwrite)) { | |
# | |
# File needs to be uploaded | |
# | |
$Document_ID = [guid]::NewGuid() | |
$datetime=get-date -Format "MM/dd/yy hh:mm tt" | |
write-host "Uploading File:" $_.FullName "to" $DestSPFile -foregroundcolor Green | |
try { | |
$web.AllowUnsafeUpdates = $true | |
$metadata = @{} | |
$metadata.add("Claim_Number", $ccnum) | |
$metadata.add("Claim_Type", $cctype) | |
$metadata.add("Freight_Bill_Pro_Number", $ccfbpn) | |
$metadata.add("Document_Id", $Document_ID.ToString()); | |
$FileStream = $_.OpenRead() | |
$spFile = $RelFolder.Files.Add($DestSPFile, $FileStream, $Metadata, $true) | |
$FileStream.Dispose() | |
$spfile.item["Title"]=$SPFileName | |
$spfile.item.Update() | |
$web.AllowUnsafeUpdates = $false | |
$RelItemPath = Convert-Path $_ | |
$RelItemPath = $RelItemPath.Substring(($RelItemPath).indexof(($RelItemPath).Split("\")[4])) | |
$DestinationPath = "P:\Local_KC\IT\New NET Env\CargoClaim_Test_II\" + $RelItemPath.Substring(0,$RelItemPath.LastIndexOf("\")) | |
$Destination = "P:\Local_KC\IT\New NET Env\CargoClaim_Test_II\" + $RelItemPath | |
} catch [System.SystemException] { | |
write-host "Error Uploading File: "$_.Message | |
} | |
$spItem = $spFile.Item | |
$SqlText += "`r`n SELECT $ccid,'$Document_ID','$Leaf','$datetime','spadmin' `r`n UNION" | |
#Check in file to document library (if required) | |
#MinorCheckIn=0, MajorCheckIn=1, OverwriteCheckIn=2 | |
if ($CheckIn) { | |
if ($spFile.CheckOutStatus -ne "None") { | |
try { | |
$spFile.CheckIn("File copied from " + $filePath, 1) | |
write-host $spfile.Name"checked in" | |
} catch [System.SystemException] { | |
write-host "Error CheckIn File: "$_.Message | |
} | |
} | |
} | |
#Approve file (if required) | |
if ($Approve) { | |
if ($spItem.ListItems.List.EnableModeration -eq $true) { | |
try { | |
$spFile.Approve("File automatically approved after copying from " + $filePath) | |
} catch [System.SystemException] { | |
write-host "Error Approving File: "$_.Message | |
} | |
if ($spItem["Approval Status"] -eq 0) { write-host $spfile.Name"approved" } | |
} | |
} | |
} | |
else | |
{ | |
write-host $SPFilename "already exists in" DestSPPath "and shall not be uploaded" -foregroundcolor Red | |
} | |
} | |
# robocopy.exe "$_.FullName" "$Destination" | |
New-Item $DestinationPath -ItemType directory -Force | |
Copy-Item $_.FullName -destination $destination | |
} | |
} | |
catch [System.SystemException] | |
{ | |
write-host "The " $_.Name " file failed: " $_.Message | |
} | |
} | |
} | |
catch [System.SystemException] | |
{ | |
write-host "The script has stopped because there has been an error: "$_.Message | |
} | |
finally | |
{ | |
$web.Dispose() | |
$datetime=get-date -Format "yyyyMMddhhmm" | |
$sqltext = $SqlText.TrimEnd('U','N','I','O','N') | |
$sqltext | Out-File D:\tools\sharepoint\reports\CC_sqltext_$datetime.txt | |
$emailfrom = $env:computername+"@miq.com" | |
$emailto = "mei.wong@miq.com" | |
Send-MailMessage -to $emailto -from $emailfrom -subject "CargoClaims SQL Statement" -bodyashtml "see attachments" -SmtpServer "usopkvsmail01" -Attachments "D:\tools\sharepoint\reports\CC_sqltext_$datetime.txt" | |
} | |
#$RelItemPath.Dispose() | |
#foreach ($file in $files) { | |
} | |
function Fix-IllegalCharacters ($Filename) | |
{ | |
#Got this from http://powershell.com/cs/blogs/tips/archive/2011/05/20/finding-multiple-regex-matches.aspx | |
$illegalChars = '[&\{\}~#%\*:<>\?\|"\[\]]' | |
filter Matches($illegalChars) | |
{ | |
$Filename | Select-String -AllMatches $illegalChars | | |
Select-Object -ExpandProperty Matches | |
Select-Object -ExpandProperty Values | |
} | |
#$SqlText -replace ".{5}$" | |
#Replace illegal characters with legal characters where found | |
[string]$NewFileName = $Filename | |
$NewFileName = $NewFileName.Replace("&","And") | |
$NewFileName = $NewFileName.Replace("{","(") | |
$NewFileName = $NewFileName.Replace("}",")") | |
$NewFileName = $NewFileName.Replace("~","-") | |
$NewFileName = $NewFileName -replace "$([char]35)", "_" | |
$NewFileName = $NewFileName.Replace("%","_") | |
$NewFileName = $NewFileName.Replace("*","_") | |
$NewFileName = $NewFileName.Replace(":","_") | |
$NewFileName = $NewFileName.Replace("<","(") | |
$NewFileName = $NewFileName.Replace(">",")") | |
$NewFileName = $NewFileName.Replace("?","_") | |
$NewFileName = $NewFileName.Replace("|","_") | |
$NewFileName = $NewFileName.Replace('"',"'") | |
$NewFileName = $NewFileName.Replace("[","(") | |
$NewFileName = $NewFileName.Replace("]",")") | |
$NewFileName = $NewFileName.Replace(". "," ") | |
#Check for start, end and double periods | |
if ($NewFileName.StartsWith(".")) { Write-Host $type $item.FullName starts with a period -ForegroundColor red } | |
while ($NewFileName.StartsWith(".")) { $NewFileName = $NewFileName.TrimStart(".") } | |
if ($NewFileName.EndsWith(".")) { Write-Host $type $item.FullName ends with a period -ForegroundColor Red } | |
while ($NewFileName.EndsWith(".")) { $NewFileName = $NewFileName.TrimEnd(".") } | |
if ($NewFileName.Contains("..")) { Write-Host $type $item.FullName contains double periods -ForegroundColor red } | |
while ($NewFileName.Contains("..")) { $NewFileName = $NewFileName.Replace("..", ".") } | |
if ($NewFileName.StartsWith("-")) { Write-Host $type $item.FullName starts with a dash -ForegroundColor red } | |
while ($NewFileName.StartsWith("-")) { $NewFileName = $NewFileName.TrimStart("-") } | |
if ($NewFileName.StartsWith("$")) { Write-Host $type $item.FullName starts with a dash -ForegroundColor red } | |
while ($NewFileName.StartsWith("$")) { $NewFileName = $NewFileName.TrimStart("$") } | |
return $NewFileName | |
} | |
#write-host "SharePoint 2010 Multiple File Upload Script - Get-SPScripts.com" | |
#Copy-FilestoSP -LocalPath “P:\Local_KC\CM Shared" -LocalFilter "*.*" -SiteUrl "http://mygateway.miq.com/libraries/CarrierServices" -Library "Documents" -LibraryStartFolder “/CM Shared” -IncludeSubFolders #-LocalFilter "*signed*.*" | |
Copy-FilestoSP -LocalPath “P:\KC Cargo Claims\Claim Scans" -LocalFilter "*.*" -SiteUrl "http://mygateway.miq.com/libraries/CargoClaims" -Library "Claims Document Library" -LibraryStartFolder “” -IncludeSubFolders -FlattenStructure |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment