SharePoint:按常规计划自动从网络共享导入文档的脚本

SharePoint:按常规计划自动从网络共享导入文档的脚本,sharepoint,powershell,sharepoint-2010,windows-services,Sharepoint,Powershell,Sharepoint 2010,Windows Services,我是SharePoint开发新手 我正在尝试自动化以下任务: 将文档从网络共享上载到SharePoint文档库 每个文件的相关元数据也需要放入SharePoint列中。(将取自同一位置的单个CSV文件,其中映射了文件名) 此过程需要按照预定义的计划自动运行(例如:每天/每小时一次等) 我想知道: 实现这一目标的最佳方式是什么?(在Windows任务计划程序上运行的PowerShell脚本,创建服务等) 编码的起点或任何已经可用的代码,因为这看起来可能是一个非常常见的需求 通常,StackO

我是SharePoint开发新手

我正在尝试自动化以下任务:

  • 将文档从网络共享上载到SharePoint文档库
  • 每个文件的相关元数据也需要放入SharePoint列中。(将取自同一位置的单个CSV文件,其中映射了文件名)
  • 此过程需要按照预定义的计划自动运行(例如:每天/每小时一次等)
我想知道:

  • 实现这一目标的最佳方式是什么?(在Windows任务计划程序上运行的PowerShell脚本,创建服务等)
  • 编码的起点或任何已经可用的代码,因为这看起来可能是一个非常常见的需求

通常,StackOverflow是提出此类问题的错误地点。但是,由于我刚刚完成创建一个脚本,用于将文件从CSV上传到SharePoint,我想我可以共享它

免责声明:我不保证这将与您的环境一起工作,或者不会把事情搞砸。复习。理解它。自担风险使用

脚本可以轻松更改为添加/更改列(在
#添加列信息
部分下)

CSV文件格式:

SubFolder,Name,Column1,Column2
如果源文件位于源文件夹的根目录上,则其中子文件夹可以为空。Name是文件名,Column1和Column2是SharePoint列

将以下代码保存到两个PowerShell文件中
importsfromcsv.ps1
包含逻辑,
Run\u importsfromcsv.ps1
包含运行它的代码

要运行,请在SharePoint服务器(或具有SharePoint PowerShell模块的服务器)上设置计划任务,并使用以下命令运行:

powershell.exe -file "C:\scripts\Run_ImportSPfromCSV.ps1"
运行\u importsfromcsv.ps1

    # Load  Script
    . .\ImportSPfromCSV.ps1 

    # Run Function
    Import-SPData -CSVFilePath "CSVFile.csv" -SourceFolder "C:\temp" -SiteURL "http://SharePointWebApp/sites/SiteCollection" -Library "Shared Documents" -Approve $true -CheckIn $true -Overwrite $false -OverwriteFields $true
<#
.SYNOPSIS
    Imports items into SharePoint library from a CSV File
.DESCRIPTION
    Imports items that are saved to disk into SharePoint library 
    using and tagging the information from a CSV File
.NOTES
    NAME:           ImportSPfromCSV.ps1
    AUTHOR:         Kristoph Minchau
    CREATED:        May 2, 2013
    LASTEDIT:   2014-03-06
    VERSION:        1.10
    KEYWORDS:       SharePoint

    REVISION LOG:
    [2013/05/01] - km - v1.00 ** Created **
    [2014-03-06] - km - v1.10 * Minor edits

.EXAMPLE
    # Load  Script
    . .\ImportSPfromCSV.ps1 

    # Run Function
    Import-SPData -CSVFilePath "CSVFile.csv" -SourceFolder "C:\temp" -SiteURL "http://SharePointWebApp/sites/SiteCollection" -Library "Shared Documents" -Approve $true -CheckIn $true -Overwrite $false -OverwriteFields $true
.LINK
    Import-SPData
#>


Add-PSSnapin Microsoft.SharePoint.Powershell -ErrorAction SilentlyContinue



<#
.SYNOPSIS
    Get SharePoint file
.DESCRIPTION
    Gets a SharePoint File
.PARAMETER SPFileName
    The file name to Upload to the SharePoint library if different than original File name
    ex. "NewName.docx"
    [String]
.PARAMETER Web
    The SharePoint web site
    [Microsoft.SharePoint.SPWeb]
.PARAMETER Library
    The Destination Library on SharePoint
    Default value = "Retail Banking"
.INPUTS
    System.String SPFileName
.OUTPUTS
    System.String Return SPFile
.EXAMPLE
    $Web = Get-SPWeb "http://SharePointWebApp/sites/SiteCollection"
    Get-SPFile -Web $Web -Library "Shared Documents" -SPFileName "File1.doc"
.LINK
    Get-SPFile
#>
Function Get-SPFile {
    [CmdletBinding()]
    Param(
        [Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
            [string]$SPFileName,
        [Parameter(Position=1, Mandatory=$true)]
            [Microsoft.SharePoint.SPWeb]$Web,
        [Parameter(Position=2, Mandatory=$true)]
            [string]$Library = "Shared Documents"
    ) #end param
    Process
    {
        Try
        {
            # Get Library
            $docLibrary = $web.Lists[$Library]
            $folder = $docLibrary.RootFolder

            # Assign the new document name, and build the destination SharePoint path
            $SPFilePath = ($folder.URL + "/" + $SPFileName)

            #Check if the file exists and the overwrite option is selected before adding the file
            $spFile = $web.GetFile($SPFilePath)

            #Return SP File
            Write-Output $spFile

        } #end Try
        Catch
        {
            Write-Error $Error[0]
        }
    } #end Process
} #end Get-SPFile



<#
.SYNOPSIS
    Adds a file to SharePoint Document Library.
.DESCRIPTION
    Adds a file to SharePoint Document Library, optionally checks it in, approve it, or overwrite it.
.PARAMETER FilePath
    The file to Upload
    ex. "c:\Test.docx"
    [String]
.PARAMETER SPFileName
    The file name to Upload to the SharePoint library. 
    Rename the File to something that is SharePoint/URL friendly (e.g. remove special characters "/?=<>" etc.)
    ex. "NewName.docx"
    [String]
.PARAMETER Web
    The SharePoint web site
    [Microsoft.SharePoint.SPWeb]
.PARAMETER Library
    The Destination Library on SharePoint
    [String]
.PARAMETER Approve
    If approval workflow is enabled, when uploading the document, approve the uploaded document
    [bool] Default value = $true
.PARAMETER CheckIn
    If workflow is enabled, when uploading the document, CheckIn the uploaded document
    [bool] Default value = $true
.PARAMETER Overwrite
    When uploading the document, if a document with the same name is encountered, overwrite the document?
    [bool] Default value = $false
.INPUTS
    N/A - Pipeline Inputs
.OUTPUTS
    SP File
.EXAMPLE
    $Web = Get-SPWeb "http://SharePointWebApp/sites/SiteCollection"
    Add-SPFileToLibrary -File "Test.docx" -SPFileName "NewName.docx" -Web $Web -Library "Shared Documents" -Approve $true -CheckIn $true -Overwrite $false
.LINK
    Add-SPFileToLibrary
#>
Function Add-SPFileToLibrary {
    [CmdletBinding()]
    Param(
        [Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
            [string]$FilePath,
        [Parameter(Position=1, Mandatory=$true)]
            [string]$SPFileName,
        [Parameter(Position=2, Mandatory=$true)]
            [Microsoft.SharePoint.SPWeb]$Web,
        [Parameter(Position=3, Mandatory=$true)]
            [string]$Library,
        [Parameter(Position=4, Mandatory=$true)]
            [bool]$Approve = $true,
        [Parameter(Position=5, Mandatory=$true)]
            [bool]$CheckIn = $true,
        [Parameter(Position=6, Mandatory=$true)]
            [bool]$Overwrite = $false
    ) #end param
    Process
    {
        Try
        {
            # Get Library
            $docLibrary = $web.Lists[$Library]
            $folder = $docLibrary.RootFolder

            # Assign the new document name, and build the destination SharePoint path
            $SPFilePath = ($folder.URL + "/" + $SPFileName)

            #Check if the file exists and the overwrite option is selected before adding the file
            if ((!$web.GetFile($SPFilePath).Exists) -or ($Overwrite))
            {
                $Message = "Uploading...   $FilePath   ...To...   $SPFilePath"
                Write-Debug $Message
                Write-Verbose $Message

                #Support for -WhatIf parameter
                if($PsCmdlet.ShouldProcess($Message))
                {
                    Write-Host $Message

                    #Upload file
                    $File = Get-ChildItem $FilePath
                    $spFile = $folder.Files.Add($SPFilePath, $File.OpenRead(), $true)  #Upload with overwrite = $true (SP file path, File stream, Overwrite?)

                    $spItem = $spFile.Item

                    #Check in file to document library (if required)
                    #MinorCheckIn=0, MajorCheckIn=1, OverwriteCheckIn=2
                    If ($CheckIn) {
                        If ($spFile.CheckOutStatus -ne "None") {
                            If ($Overwrite){
                                #$spFile.CheckIn("File copied from " + $filePath, 2)
                                $spFile.CheckIn("Version 1.0", 2)
                            }
                            Else
                            {
                                #$spFile.CheckIn("File copied from " + $filePath, 1)
                                $spFile.CheckIn("Version 1.0", 1)
                            }
                            Write-Host "$spfile.Name Checked In"
                        }
                    } #end CheckIn

                    #Approve file (if required)
                    If ($Approve)
                    {
                        If ($spItem.ListItems.List.EnableModeration -eq $true)
                        {
                            #$spFile.Approve("File automatically approved after copying from " + $filePath)
                            $spFile.Approve("Approved")
                            If ($spFile.Item["Approval Status"] -eq 0)
                            {
                                Write-Host "$spfile.Name Approved"
                            }
                            Else
                            {
                                Write-Host -Background Yellow -Foreground Black "Warning: $spfile.Name Not Approved"
                            }
                        }
                    } #end Approve

                    #Return SP File
                    Write-Output $spFile

                }# end upload file
            }
            Else
            {
                If($web.GetFile($SPFilePath).Exists)
                {
                    Write-Verbose "File Exists and Overwrite = $false returning file"
                    # File Exists and Overwrite = $false, Try finding and returning the file
                    $spFile = Get-SPFile -Web $web -Library $Library -SPFileName $SPFileName

                    #Return SP File
                    Write-Output $spFile
                }
                else
                {
                    # File does not exist, and Overwrite = $false, we can't return anything, Throw Warning
                    Write-Host -Background Yellow -Foreground Black "Warning: $SPFilePath does not Exist and Overwrite is set to False. No SP File handle returned"
                    Write-Output $null
                }
            }# end File Exists and Overwrite Check

        } #end Try
        Catch
        {
            Write-Error $Error[0]
        }
    } #end Process
} #end Add-SPFileToLibrary





<#
.SYNOPSIS
    Imports files into SharePoint library from a CSV File
.DESCRIPTION
    Imports files that are saved to disk into SharePoint library 
    using and tagging the information from a CSV File
.PARAMETER CSVFilePath
    The CSV import file to use to import the data from
    Default value = "CSVFile.csv"
.PARAMETER SourceFolder
    The Source Folder for locating the Public Folder files
    Default value = "."
.PARAMETER SiteURL
    The Site URL on SharePoint
    Default value = "http://SharePointWebApp/sites/SiteCollection"
.PARAMETER Library
    The Destination Library on SharePoint
    Default value = "Shared Documents"
.PARAMETER Approve
    If approval workflow is enabled, when uploading the document, approve the uploaded document
    [bool] Default value = $true
.PARAMETER CheckIn
    If workflow is enabled, when uploading the document, CheckIn the uploaded document
    [bool] Default value = $true
.PARAMETER Overwrite
    When uploading the document, if a document with the same name is encountered, overwrite the document?
    [bool] Default value = $false
.PARAMETER OverwriteFields
    If the document is already uploaded, overwrite the fields with the fields from the CSV file
    [bool] Default value = $true
.INPUTS
    N/A - Pipeline Inputs
.OUTPUTS
    System.String Returns
.EXAMPLE
    #Default Initial Import of all data
    Import-SPData -CSVFilePath "CSVFile.csv" -SourceFolder "C:\temp" -SiteURL "http://SharePointWebApp/sites/SiteCollection" -Library "Shared Documents" -Approve $true -CheckIn $true -Overwrite $false -OverwriteFields $true
.LINK
    Import-SPData
#>
Function Import-SPData {
    [CmdletBinding()]
    Param(
        [Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
            [string]$CSVFilePath = "CSVFile.csv",
        [Parameter(Position=1, Mandatory=$true)]
            [string]$SourceFolder = ".",
        [Parameter(Position=2, Mandatory=$true)]
            [string]$SiteURL = "http://SharePointWebApp/sites/SiteCollection",
        [Parameter(Position=3, Mandatory=$true)]
            [string]$Library = "Shared Documents",
        [Parameter(Position=4, Mandatory=$true)]
            [bool]$Approve = $true,
        [Parameter(Position=5, Mandatory=$true)]
            [bool]$CheckIn = $true,
        [Parameter(Position=6, Mandatory=$true)]
            [bool]$Overwrite = $false,
        [Parameter(Position=7, Mandatory=$true)]
            [bool]$OverwriteFields = $true
    ) #end param
    Process
    {
        Try
        {
            #Get Web
            $web = Get-SPWeb $SiteUrl

            Write-Host -Background Black -Foreground Green "Uploading Documents..."

            # Loop through the CSV file entries
            Import-Csv $CSVFilePath | ForEach-Object{

                # File Path
                if($_.Subfolder)
                {
                    #Subfolder exists
                    $FilePath = ($SourceFolder + "\" + $_.Subfolder + "\" + $_.Name)
                }
                else
                {
                    #Subfolder does not exist
                    $FilePath = ($SourceFolder + "\" + $_.Name)
                }

                # Assign the new document name, and build the destination SharePoint path
                $SPFileName = $_.Name

                # Add the file to the SP Library. Don't approve or check in yet because we have to change the column values.
                $spFile = Add-SPFileToLibrary -FilePath $FilePath -SPFileName $SPFileName -Web $web -Library $Library -Approve $Approve -CheckIn $CheckIn -Overwrite $Overwrite

                if($spFile -And $OverwriteFields)
                {
                    $spItem = $spFile.Item

                    $Message = "Changing column values for $($_.Name) ..."
                    Write-Debug $Message
                    Write-Verbose $Message

                    #Support for -WhatIf parameter
                    if($PsCmdlet.ShouldProcess($Message))
                    {
                        Write-Host $Message

                        #Add Column Information
                        Try
                        {
                            # Column1
                            Write-Verbose "Setting Column1 to $($_.Column1)"
                            $spItem["Column1"] = $($_.Column1)

                            # Column2
                            Write-Verbose "Setting Column1 to $($_.Column2)"
                            $spItem["Column2"] = $($_.Column2)

                            #Update document with new column values
                            $spItem.SystemUpdate($false)

                            Write-Host "...Complete"
                        }
                        Catch
                        {
                            Write-Error "Error Changing Column information"
                            Write-Error $Error[0]
                        }
                    }#end Change Column values
                }
                else
                {
                    if($OverwriteFields)
                    {
                        # No file handle returned
                        Write-Host -Background DarkRed -ForeGround Yellow "Error: File not uploaded or no File handle returned: $_.Name"
                    }
                    else
                    {
                        # File handle returned, but OverwriteFields = $false
                        Write-Verbose "Not modifying any columns for $_.Name"
                    }
                }#end if $spFile is set to something and OverwriteFields = $true
            } #end CSV loop
        } #end Try
        Catch
        {
            Write-Error $Error[0]
        }
    } #end Process
} #end function Import-SPData
导入pfromcsv.ps1

    # Load  Script
    . .\ImportSPfromCSV.ps1 

    # Run Function
    Import-SPData -CSVFilePath "CSVFile.csv" -SourceFolder "C:\temp" -SiteURL "http://SharePointWebApp/sites/SiteCollection" -Library "Shared Documents" -Approve $true -CheckIn $true -Overwrite $false -OverwriteFields $true
<#
.SYNOPSIS
    Imports items into SharePoint library from a CSV File
.DESCRIPTION
    Imports items that are saved to disk into SharePoint library 
    using and tagging the information from a CSV File
.NOTES
    NAME:           ImportSPfromCSV.ps1
    AUTHOR:         Kristoph Minchau
    CREATED:        May 2, 2013
    LASTEDIT:   2014-03-06
    VERSION:        1.10
    KEYWORDS:       SharePoint

    REVISION LOG:
    [2013/05/01] - km - v1.00 ** Created **
    [2014-03-06] - km - v1.10 * Minor edits

.EXAMPLE
    # Load  Script
    . .\ImportSPfromCSV.ps1 

    # Run Function
    Import-SPData -CSVFilePath "CSVFile.csv" -SourceFolder "C:\temp" -SiteURL "http://SharePointWebApp/sites/SiteCollection" -Library "Shared Documents" -Approve $true -CheckIn $true -Overwrite $false -OverwriteFields $true
.LINK
    Import-SPData
#>


Add-PSSnapin Microsoft.SharePoint.Powershell -ErrorAction SilentlyContinue



<#
.SYNOPSIS
    Get SharePoint file
.DESCRIPTION
    Gets a SharePoint File
.PARAMETER SPFileName
    The file name to Upload to the SharePoint library if different than original File name
    ex. "NewName.docx"
    [String]
.PARAMETER Web
    The SharePoint web site
    [Microsoft.SharePoint.SPWeb]
.PARAMETER Library
    The Destination Library on SharePoint
    Default value = "Retail Banking"
.INPUTS
    System.String SPFileName
.OUTPUTS
    System.String Return SPFile
.EXAMPLE
    $Web = Get-SPWeb "http://SharePointWebApp/sites/SiteCollection"
    Get-SPFile -Web $Web -Library "Shared Documents" -SPFileName "File1.doc"
.LINK
    Get-SPFile
#>
Function Get-SPFile {
    [CmdletBinding()]
    Param(
        [Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
            [string]$SPFileName,
        [Parameter(Position=1, Mandatory=$true)]
            [Microsoft.SharePoint.SPWeb]$Web,
        [Parameter(Position=2, Mandatory=$true)]
            [string]$Library = "Shared Documents"
    ) #end param
    Process
    {
        Try
        {
            # Get Library
            $docLibrary = $web.Lists[$Library]
            $folder = $docLibrary.RootFolder

            # Assign the new document name, and build the destination SharePoint path
            $SPFilePath = ($folder.URL + "/" + $SPFileName)

            #Check if the file exists and the overwrite option is selected before adding the file
            $spFile = $web.GetFile($SPFilePath)

            #Return SP File
            Write-Output $spFile

        } #end Try
        Catch
        {
            Write-Error $Error[0]
        }
    } #end Process
} #end Get-SPFile



<#
.SYNOPSIS
    Adds a file to SharePoint Document Library.
.DESCRIPTION
    Adds a file to SharePoint Document Library, optionally checks it in, approve it, or overwrite it.
.PARAMETER FilePath
    The file to Upload
    ex. "c:\Test.docx"
    [String]
.PARAMETER SPFileName
    The file name to Upload to the SharePoint library. 
    Rename the File to something that is SharePoint/URL friendly (e.g. remove special characters "/?=<>" etc.)
    ex. "NewName.docx"
    [String]
.PARAMETER Web
    The SharePoint web site
    [Microsoft.SharePoint.SPWeb]
.PARAMETER Library
    The Destination Library on SharePoint
    [String]
.PARAMETER Approve
    If approval workflow is enabled, when uploading the document, approve the uploaded document
    [bool] Default value = $true
.PARAMETER CheckIn
    If workflow is enabled, when uploading the document, CheckIn the uploaded document
    [bool] Default value = $true
.PARAMETER Overwrite
    When uploading the document, if a document with the same name is encountered, overwrite the document?
    [bool] Default value = $false
.INPUTS
    N/A - Pipeline Inputs
.OUTPUTS
    SP File
.EXAMPLE
    $Web = Get-SPWeb "http://SharePointWebApp/sites/SiteCollection"
    Add-SPFileToLibrary -File "Test.docx" -SPFileName "NewName.docx" -Web $Web -Library "Shared Documents" -Approve $true -CheckIn $true -Overwrite $false
.LINK
    Add-SPFileToLibrary
#>
Function Add-SPFileToLibrary {
    [CmdletBinding()]
    Param(
        [Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
            [string]$FilePath,
        [Parameter(Position=1, Mandatory=$true)]
            [string]$SPFileName,
        [Parameter(Position=2, Mandatory=$true)]
            [Microsoft.SharePoint.SPWeb]$Web,
        [Parameter(Position=3, Mandatory=$true)]
            [string]$Library,
        [Parameter(Position=4, Mandatory=$true)]
            [bool]$Approve = $true,
        [Parameter(Position=5, Mandatory=$true)]
            [bool]$CheckIn = $true,
        [Parameter(Position=6, Mandatory=$true)]
            [bool]$Overwrite = $false
    ) #end param
    Process
    {
        Try
        {
            # Get Library
            $docLibrary = $web.Lists[$Library]
            $folder = $docLibrary.RootFolder

            # Assign the new document name, and build the destination SharePoint path
            $SPFilePath = ($folder.URL + "/" + $SPFileName)

            #Check if the file exists and the overwrite option is selected before adding the file
            if ((!$web.GetFile($SPFilePath).Exists) -or ($Overwrite))
            {
                $Message = "Uploading...   $FilePath   ...To...   $SPFilePath"
                Write-Debug $Message
                Write-Verbose $Message

                #Support for -WhatIf parameter
                if($PsCmdlet.ShouldProcess($Message))
                {
                    Write-Host $Message

                    #Upload file
                    $File = Get-ChildItem $FilePath
                    $spFile = $folder.Files.Add($SPFilePath, $File.OpenRead(), $true)  #Upload with overwrite = $true (SP file path, File stream, Overwrite?)

                    $spItem = $spFile.Item

                    #Check in file to document library (if required)
                    #MinorCheckIn=0, MajorCheckIn=1, OverwriteCheckIn=2
                    If ($CheckIn) {
                        If ($spFile.CheckOutStatus -ne "None") {
                            If ($Overwrite){
                                #$spFile.CheckIn("File copied from " + $filePath, 2)
                                $spFile.CheckIn("Version 1.0", 2)
                            }
                            Else
                            {
                                #$spFile.CheckIn("File copied from " + $filePath, 1)
                                $spFile.CheckIn("Version 1.0", 1)
                            }
                            Write-Host "$spfile.Name Checked In"
                        }
                    } #end CheckIn

                    #Approve file (if required)
                    If ($Approve)
                    {
                        If ($spItem.ListItems.List.EnableModeration -eq $true)
                        {
                            #$spFile.Approve("File automatically approved after copying from " + $filePath)
                            $spFile.Approve("Approved")
                            If ($spFile.Item["Approval Status"] -eq 0)
                            {
                                Write-Host "$spfile.Name Approved"
                            }
                            Else
                            {
                                Write-Host -Background Yellow -Foreground Black "Warning: $spfile.Name Not Approved"
                            }
                        }
                    } #end Approve

                    #Return SP File
                    Write-Output $spFile

                }# end upload file
            }
            Else
            {
                If($web.GetFile($SPFilePath).Exists)
                {
                    Write-Verbose "File Exists and Overwrite = $false returning file"
                    # File Exists and Overwrite = $false, Try finding and returning the file
                    $spFile = Get-SPFile -Web $web -Library $Library -SPFileName $SPFileName

                    #Return SP File
                    Write-Output $spFile
                }
                else
                {
                    # File does not exist, and Overwrite = $false, we can't return anything, Throw Warning
                    Write-Host -Background Yellow -Foreground Black "Warning: $SPFilePath does not Exist and Overwrite is set to False. No SP File handle returned"
                    Write-Output $null
                }
            }# end File Exists and Overwrite Check

        } #end Try
        Catch
        {
            Write-Error $Error[0]
        }
    } #end Process
} #end Add-SPFileToLibrary





<#
.SYNOPSIS
    Imports files into SharePoint library from a CSV File
.DESCRIPTION
    Imports files that are saved to disk into SharePoint library 
    using and tagging the information from a CSV File
.PARAMETER CSVFilePath
    The CSV import file to use to import the data from
    Default value = "CSVFile.csv"
.PARAMETER SourceFolder
    The Source Folder for locating the Public Folder files
    Default value = "."
.PARAMETER SiteURL
    The Site URL on SharePoint
    Default value = "http://SharePointWebApp/sites/SiteCollection"
.PARAMETER Library
    The Destination Library on SharePoint
    Default value = "Shared Documents"
.PARAMETER Approve
    If approval workflow is enabled, when uploading the document, approve the uploaded document
    [bool] Default value = $true
.PARAMETER CheckIn
    If workflow is enabled, when uploading the document, CheckIn the uploaded document
    [bool] Default value = $true
.PARAMETER Overwrite
    When uploading the document, if a document with the same name is encountered, overwrite the document?
    [bool] Default value = $false
.PARAMETER OverwriteFields
    If the document is already uploaded, overwrite the fields with the fields from the CSV file
    [bool] Default value = $true
.INPUTS
    N/A - Pipeline Inputs
.OUTPUTS
    System.String Returns
.EXAMPLE
    #Default Initial Import of all data
    Import-SPData -CSVFilePath "CSVFile.csv" -SourceFolder "C:\temp" -SiteURL "http://SharePointWebApp/sites/SiteCollection" -Library "Shared Documents" -Approve $true -CheckIn $true -Overwrite $false -OverwriteFields $true
.LINK
    Import-SPData
#>
Function Import-SPData {
    [CmdletBinding()]
    Param(
        [Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
            [string]$CSVFilePath = "CSVFile.csv",
        [Parameter(Position=1, Mandatory=$true)]
            [string]$SourceFolder = ".",
        [Parameter(Position=2, Mandatory=$true)]
            [string]$SiteURL = "http://SharePointWebApp/sites/SiteCollection",
        [Parameter(Position=3, Mandatory=$true)]
            [string]$Library = "Shared Documents",
        [Parameter(Position=4, Mandatory=$true)]
            [bool]$Approve = $true,
        [Parameter(Position=5, Mandatory=$true)]
            [bool]$CheckIn = $true,
        [Parameter(Position=6, Mandatory=$true)]
            [bool]$Overwrite = $false,
        [Parameter(Position=7, Mandatory=$true)]
            [bool]$OverwriteFields = $true
    ) #end param
    Process
    {
        Try
        {
            #Get Web
            $web = Get-SPWeb $SiteUrl

            Write-Host -Background Black -Foreground Green "Uploading Documents..."

            # Loop through the CSV file entries
            Import-Csv $CSVFilePath | ForEach-Object{

                # File Path
                if($_.Subfolder)
                {
                    #Subfolder exists
                    $FilePath = ($SourceFolder + "\" + $_.Subfolder + "\" + $_.Name)
                }
                else
                {
                    #Subfolder does not exist
                    $FilePath = ($SourceFolder + "\" + $_.Name)
                }

                # Assign the new document name, and build the destination SharePoint path
                $SPFileName = $_.Name

                # Add the file to the SP Library. Don't approve or check in yet because we have to change the column values.
                $spFile = Add-SPFileToLibrary -FilePath $FilePath -SPFileName $SPFileName -Web $web -Library $Library -Approve $Approve -CheckIn $CheckIn -Overwrite $Overwrite

                if($spFile -And $OverwriteFields)
                {
                    $spItem = $spFile.Item

                    $Message = "Changing column values for $($_.Name) ..."
                    Write-Debug $Message
                    Write-Verbose $Message

                    #Support for -WhatIf parameter
                    if($PsCmdlet.ShouldProcess($Message))
                    {
                        Write-Host $Message

                        #Add Column Information
                        Try
                        {
                            # Column1
                            Write-Verbose "Setting Column1 to $($_.Column1)"
                            $spItem["Column1"] = $($_.Column1)

                            # Column2
                            Write-Verbose "Setting Column1 to $($_.Column2)"
                            $spItem["Column2"] = $($_.Column2)

                            #Update document with new column values
                            $spItem.SystemUpdate($false)

                            Write-Host "...Complete"
                        }
                        Catch
                        {
                            Write-Error "Error Changing Column information"
                            Write-Error $Error[0]
                        }
                    }#end Change Column values
                }
                else
                {
                    if($OverwriteFields)
                    {
                        # No file handle returned
                        Write-Host -Background DarkRed -ForeGround Yellow "Error: File not uploaded or no File handle returned: $_.Name"
                    }
                    else
                    {
                        # File handle returned, but OverwriteFields = $false
                        Write-Verbose "Not modifying any columns for $_.Name"
                    }
                }#end if $spFile is set to something and OverwriteFields = $true
            } #end CSV loop
        } #end Try
        Catch
        {
            Write-Error $Error[0]
        }
    } #end Process
} #end function Import-SPData

在Microsoft.SharePoint.Powershell中添加PSSnapin-ErrorAction SilentlyContinue
函数获取SPFile{
[CmdletBinding()]
Param(
[参数(位置=0,必需=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[string]$SPFileName,
[参数(位置=1,强制=true)]
[Microsoft.SharePoint.SPWeb]$Web,
[参数(位置=2,强制=true)]
[string]$Library=“共享文档”
)#结束参数
过程
{
尝试
{
#获取库
$docLibrary=$web.Lists[$Library]
$folder=$docLibrary.RootFolder
#分配新文档名,并生成目标SharePoint路径
$SPFilePath=($folder.URL+“/”+$SPFileName)
#添加文件之前,请检查文件是否存在,并选择覆盖选项
$spFile=$web.GetFile($SPFilePath)
#返回SP文件
写入输出$spFile
}#结束尝试
抓住
{
写入错误$Error[0]
}
}#结束过程
}#结束获取SPFile
函数Add SPFileToLibrary{
[CmdletBinding()]
Param(
[参数(位置=0,必需=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[string]$FilePath,
[参数(位置=1,强制=true)]
[string]$SPFileName,
[参数(位置=2,强制=true)]
[Microsoft.SharePoint.SPWeb]$Web,
[参数(位置=3,强制=true)]
[string]$Library,
[参数(位置=4,强制=true)]
[bool]$Approve=$true,
[参数(位置=5,强制=true)]
[bool]$CheckIn=$true,
[参数(位置=6,强制=true)]
[bool]$Overwrite=$false
)#结束参数
过程
{
尝试
{
#获取库
$docLibrary=$web.Lists[$Library]
$folder=$docLibrary.RootFolder
#分配新文档名,并生成目标SharePoint路径
$SPFilePath=($folder.URL+“/”+$SPFileName)
#添加文件之前,请检查文件是否存在,并选择覆盖选项
如果(!$web.GetFile($SPFilePath).Exists)-或($Overwrite))
{
$Message=“正在将…$FilePath…上载到…$SPFilePath”
写入调试$消息
编写详细的$Message
#支持-WhatIf参数
if($PsCmdlet.ShouldProcess($Message))
{
写入主机$Message
#上传文件
$File=获取子项$FilePath
$spFile=$folder.Files.Add($SPFilePath,$File.OpenRead(),$true)#带覆盖的上载=$true(SP文件路径、文件流、覆盖?)
$spItem=$spFile.Item
#将文件检入文档库(如果需要)
#MinorCheckIn=0,MajorCheckIn=1,OverwriteCheckIn=2
如果($签入){
如果($spFile.CheckOutStatus-ne“无”){
如果($覆盖){
#$spFile.CheckIn(“从“+$filePath,2”复制的文件)
$spFile.CheckIn(“版本1.0”,2)
}
其他的
{
#$spFile.CheckIn(“从“+$filePath,1”复制的文件)
$spFile.CheckIn(“版本1.0”,1)
}
写入主机“$spfile.Name已签入”
}
}#结束签入
#批准文件(如果需要)
如果($批准)
{
If($spItem.ListItems.List.EnableModeration-eq$true)
{
#$spFile.Approve(“文件