1

I am trying to make a script to insert some pages in SharePoint and insert data in other DB in same script

The script and errors:

    #################################################################################
# Cria novas páginas baseado em um arquivo xml e adiciona a nova funcinalidade  #
# na base Portal_ControleAcesso                                                 #
#                                                                               #
# Author: Peterson Lopes Carvalho                                               #
# Date: 25/09/2014                                                              #
#################################################################################

# carregando configurações 



$virtualDir =  Read-Host "Digite o nome do diretório virtual do site"
$config_path = "C:\inetpub\wwwroot\wss\VirtualDirectories\" + $virtualDir + "\web.config"
[System.AppDomain]::CurrentDomain.SetData("APP_CONFIG_FILE", $config_path)
[void][System.Reflection.Assembly]::LoadWithPartialName("System.Configuration")
[System.Configuration.ConfigurationManager].GetField("s_initState", [Reflection.BindingFlags] "NonPublic,Static").SetValue($null, 0)
[void][System.Reflection.Assembly]::LoadWithPartialName("System.Web")

# adicionando snap-in do sharepoint
if ((Get-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue) -eq $null) {
    Add-PSSnapin "Microsoft.SharePoint.PowerShell"
}

# lendo xml contendo as páginas a serem criadas
[xml]$pagesXML = Get-Content -Encoding UTF8 "paginas.xml"
if ($pagesXML -eq $null) { return }

# Obtendo site e publishing web
$siteUrl =  Read-Host "Digite a url do site"
$site = New-Object Microsoft.SharePoint.SPSite("$siteUrl")
$psite = New-Object Microsoft.SharePoint.Publishing.PublishingSite($site)
$web = $site.OpenWeb()
$pWeb = [Microsoft.SharePoint.Publishing.PublishingWeb]::GetPublishingWeb($web)
$pagesListName = $pweb.PagesListName

# Carregando assembly que contém as webparts
Add-Type -AssemblyName "IcatuControleAcesso, Version=1.0.0.0, Culture=neutral, PublicKeyToken=3ed9aadc2088b026"
Add-Type -AssemblyName "GestaoDocumentos, Version=1.0.0.0, Culture=neutral, PublicKeyToken=332f89a01d4ed4b0"
Add-Type -AssemblyName "System.Data.Entity, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"

# criando as páginas
$pagesXML.Pages.Page | ForEach-Object {

    # definindo nome e propriedades da página
    $pagetitle = [string]$_.PageTitle   
    $pageurl = $pagetitle + ".aspx"
    $pagelayoutName = "layout.aspx"
    $pagelayout = $psite.GetPageLayouts($false) | Where { $_.Name -eq $pagelayoutName }
    Write-Host "Criando $pagetitle" -ForegroundColor White

    # verificando se a página já existe
    $file = $web.GetFile("$pagesListName/$pageurl")
    if (-not($file.Exists)) {
        Write-Host "Página $pagetitle não encontrada. Criando..." -ForegroundColor White

        # criando a página
        $newPage = $pWeb.AddPublishingPage($pageurl, $pagelayout)
        $newPage.Update()
        $newPage.ListItem["Title"] = $pagetitle
        $newPage.ListItem.SystemUpdate()

        # obtendo webpartmanager da página
        $mgr = $web.GetLimitedWebPartManager($newPage.Url, [System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)

        # adicionando webparts
        $_.WebParts.WebPart | ForEach-Object {
            $webpart = [string]$_.WPType
            $newWebPart = new-object  $webpart
            $newWebPart.Title = $webpart.Split(".")[4]
            $mgr.AddWebPart($newWebPart, $_.Zone , $_.Index);
        }

        # adicionando webpart de integração, caso exista
        if($_.WebPartIntegracao -ne $null){
            $webpart = [string]$_.WebPartIntegracao.WPType
            $newWebPart = new-object  $webpart
            $newWebPart.Title = $webpart.Split(".")[4]
                        $newWebPart.Tipo = $_.WebPartIntegracao.Tipo
            $mgr.AddWebPart($newWebPart, $_.WebPartIntegracao.Zone , $_.WebPartIntegracao.Index);
        }



        # criando a role para a página
        [System.Web.Security.SqlRoleProvider] $roleProvider = [System.Web.Security.Roles]::Providers["IcatuRoleProvider"]
        if(-Not ($roleProvider.RoleExists($pagetitle))){
        $roleProvider.CreateRole($pagetitle);
        }
        $newUserName = "icaturoleprovider:$pagetitle"
        $member = $web.EnsureUser($newUserName)

        # criando grupo para a nova pagina
        $group = $web.SiteGroups[$pagetitle]
        if($group -eq $null){
            $web.SiteGroups.Add($pagetitle, $web.Site.Owner, $null, "")
            $group = $web.SiteGroups[$pagetitle]
        }
        $group.AddUser($member)

        # associando grupo com o site
        $roleAssignment = New-Object Microsoft.SharePoint.SPRoleAssignment($group)
        $roleDefinition = $web.RoleDefinitions["IcatuFBA"]
        $roleAssignment.RoleDefinitionBindings.Add($roleDefinition)
        $web.RoleAssignments.Add($roleAssignment)
        $web.Update()

        # associando grupo com a página
        $newPage.ListItem.BreakRoleInheritance($true)
        $roleAssigns = $newPage.ListItem.RoleAssignments;
        for ($i = $roleAssigns.Count - 1; $i -ge 0; $i--)
        {
            $roleAssigns.Remove($i);
        }
        $roleAssignment = New-Object Microsoft.SharePoint.SPRoleAssignment($group)
        $roleDefinition = $web.RoleDefinitions["IcatuFBA"]
        $roleAssignment.RoleDefinitionBindings.Add($roleDefinition)
        $newPage.ListItem.RoleAssignments.Add($roleAssignment)
        $newPage.ListItem.Update()

        # efetuando checkin e publicando a página
        $newPage.CheckIn("")
        $newPage.ListItem.File.Publish("");

        #estabelecendo conexao com banco de dados "Portal_ControleAcesso"
            $connString = [System.Configuration.ConfigurationManager]::ConnectionStrings["IcatuControleAcessoDBEntities"].ConnectionString;
            [System.Data.EntityClient.EntityConnection] $entityConn = new-object System.Data.EntityClient.EntityConnection("$connString")
            $conn = $entityConn.StoreConnection
            $conn.Open() | out-null

            $script = [string]$_.AdditionalScript


        # executando store procedure para adicionar a nova funcionalidade na base Portal_ControleAcesso
        if($_.PageReference -ne $null){

            $connString = [System.Configuration.ConfigurationManager]::ConnectionStrings["IcatuControleAcessoDBEntities"].ConnectionString;
            [System.Data.EntityClient.EntityConnection] $entityConn = new-object System.Data.EntityClient.EntityConnection("$connString")
            $conn = $entityConn.StoreConnection
            $conn.Open() | out-null
            $cmd = new-Object System.Data.SqlClient.SqlCommand("InserirNovaFuncionalidade", $conn)
            $cmd.CommandType = [System.Data.CommandType]::StoredProcedure

            $pagina = $pagetitle
            $cmd.Parameters.Add("@pagina",[system.data.SqlDbType]::NVarChar) | out-Null
            $cmd.Parameters['@pagina'].Direction = [system.data.ParameterDirection]::Input
            $cmd.Parameters['@pagina'].value = $pagina

            $paginaBase = [string]$_.PageReference
            $cmd.Parameters.Add("@paginaBase",[system.data.SqlDbType]::NVarChar) | out-Null
            $cmd.Parameters['@paginaBase'].Direction = [system.data.ParameterDirection]::Input
            $cmd.Parameters['@paginaBase'].value = $paginaBase

            $breadcrumb = [string]$_.BreadCrumb
            $cmd.Parameters.Add("@breadcrumb",[system.data.SqlDbType]::NVarChar) | out-Null
            $cmd.Parameters['@breadcrumb'].Direction = [system.data.ParameterDirection]::Input
            $cmd.Parameters['@breadcrumb'].value = $breadcrumb

            $nomeExibicao = [string]$_.DisplayName
            $cmd.Parameters.Add("@nomeExibicao",[system.data.SqlDbType]::NVarChar) | out-Null
            $cmd.Parameters['@nomeExibicao'].Direction = [system.data.ParameterDirection]::Input
            $cmd.Parameters['@nomeExibicao'].value = $nomeExibicao

            $cmd.ExecuteNonQuery()
            $conn.Close()
        }

        # executando store procedure para adicionar a nova funcionalidade na base Portal_ControleAcesso
        if($_.AdditionalScript -ne $null){


            #inserindo funcionalidades no banco
            $SqlCmd = New-Object System.Data.SqlClient.SqlCommand
            $funcs = get-content $script;
            $SqlCmd.CommandText = $funcs;
            $SqlCmd.Connection = $conn
            $SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
            $SqlAdapter.SelectCommand = $SqlCmd
            $DataSet = New-Object System.Data.DataSet
            $SqlAdapter.Fill($DataSet)

        }


        Write-Host "Página $pagetitle criada." -ForegroundColor Green
    }else{
        Write-Host "Página $pagetitle já existe." -ForegroundColor Red
    }

}

# descartando os objetos web e site
$web.Dispose()
$site.Dispose()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.