Showing posts with label Powershell. Show all posts
Showing posts with label Powershell. Show all posts

Thursday, November 22, 2012

Create SharePoint 2010 sites using PowerShell reading an XML file

 

Just a quick post to show how easy it is to create some sites in SharePoint 2010 using PowerShell by reading an XML file. I’m sure there are some powershell experts out there that can improve the code, but if you need to create a revision gateway during lunch this is the place to start.

Lets start by opening PowerShell with modules on the sharepoint server.

Create a sample xml file:

"<Setup>
<Sites>
<TopSiteName>Site1</TopSiteName>
</Sites>
<Sites>
<TopSiteName>Site2</TopSiteName>
<SubSiteName>Subsite2a</SubSiteName>
<SubSiteName>Subsite2b</SubSiteName>
</Sites>
<Sites>
<TopSiteName>Site3</TopSiteName>
<SubSiteName>Subsite3a</SubSiteName>
<SubSiteName>Subsite3b</SubSiteName>
<SubSiteName>Subsite3c</SubSiteName>
</Sites>
</Setup>" | out-file sample.xml

Now we have some data to work with we can create the sites. Three top sites will be created with 2 and 3 subsites below Site2 and Site3. They can be created using:

[xml]$s = get-content sample.xml
foreach ($e in $s.Setup.Sites){
$v = $e.TopSiteName
$b = $e.SubSiteName
new-SPWeb http://sp2010rc/$v -template "STS#0" -addtotopnav -useparenttopnav -name $v
if($b.Length -gt 0) {
foreach ($b in $b){
new-SPWeb http://sp2010rc/$v/$b -template "STS#0" -name $b -AddToQuickLaunch -useparenttopnav
}
}
}

The bit that creates the site is the new-SPWeb command. For information about the command switches run:

get-help new-SPWeb -full

It’s as easy as that! You will now have some SharePoint 2010 sites created in a matter of seconds.


To remove sites you can just use the remove-SPWeb command. This can be scripted in the same way:

[xml]$s = get-content sample.xml
foreach ($e in $s.Setup.Sites){
$v = $e.TopSiteName
$b = $e.SubSiteName
if($b.Length -gt 0) {
foreach ($b in $b){
remove-SPWeb http://sp2010rc/$v/$b
}
}
remove-SPWeb http://sp2010rc/$v

}

Friday, October 26, 2012

Import Data to List using PowerShell by csv

Add-PsSnapin Microsoft.SharePoint.Powershell –ErrorAction SilentlyContinue
$csv = Import-Csv 'E:\Sharepoint\SharepointStuff\PowershellScripts\test\w\Import.csv'

$web = Get-SPWeb -identity "http://globas"

$list = $web.Lists["News"]

foreach ($row in $csv) {
$item = $list.Items.Add();
$item["Title"] =$row.Title
$item["Body"] =$row.Body
$item["Expires"] =$row.Expires
$item.Update()
}


Write-Host "Finished! Press enter key to exit." -ForegroundColor Green
Read-Host

 

please use CSV column as Title,Body

Remove Solution from the Central admin using Poweshell

Add-PsSnapin Microsoft.SharePoint.Powershell –ErrorAction SilentlyContinue

 

Uninstall-SPSolution –Identity bamboo.logging.v1.wsp


Start-Sleep -Seconds 60

Remove-SPSolution –Identity bamboo.logging.v1.wsp

 

Uninstall-SPSolution –Identity basicwebpartssingle.wsp


Start-Sleep -Seconds 60

Remove-SPSolution –Identity basicwebpartssingle.wsp

 

Uninstall-SPSolution –Identity contentsliderwebpart.wsp


Start-Sleep -Seconds 60

Remove-SPSolution –Identity contentsliderwebpart.wsp

 

Uninstall-SPSolution –Identity mydocstreeview.wsp


Start-Sleep -Seconds 60

Remove-SPSolution –Identity mydocstreeview.wsp

 

Uninstall-SPSolution –Identity sampletodeployapage.wsp


Start-Sleep -Seconds 60

Remove-SPSolution –Identity sampletodeployapage.wsp

 

 

 


Write-Host "Finished! Press enter key to exit." -ForegroundColor Green
Read-Host

Retrieve All Wsp from the Central Admin

Add-PSSnapin Microsoft.SharePoint.PowerShell –erroraction SilentlyContinue
## setup our output directory
$dirName = "c:\ExportedSolutions"
Write-Host Exporting solutions to $dirName
foreach ($solution in Get-SPSolution)
{
    $id = $Solution.SolutionID
    $title = $Solution.Name
    $filename = $Solution.SolutionFile.Name
    Write-Host "Exporting ‘$title’ to …\$filename" -nonewline
    try {
        $solution.SolutionFile.SaveAs("$dirName\$filename")
        Write-Host " – done" -foreground green
    }
    catch
    {
        Write-Host " – error : $_" -foreground red
    }
}

Retrieve Single Wsp from the Central Admin

Add-PsSnapin Microsoft.SharePoint.Powershell –ErrorAction SilentlyContinue

$dirName = "c:\ExportedSolutions\"
if (!(Test-Path -path $dirName))
{
New-Item $dirName -type directory
}
Write-Host Exporting solution to $dirName
$farm = Get-SPFarm
$file = $farm.Solutions.Item("treeviewdocumentlibrary.wsp").SolutionFile
$file.SaveAs($dirName + "treeviewdocumentlibrary.wsp")

Automated wsp installer using Powershell

######################################
######## Set Variables ###############
######################################
$InstallDIR = "C:\install"
 
######################################
#### CODE, No Changes Necessary ######
######################################
Write-Host "Working, Please wait...."
Add-PSSnapin microsoft.sharepoint.powershell -ErrorAction SilentlyContinue
 
$Dir = get-childitem $InstallDIR -Recurse
$WSPList = $Dir | where {$_.Name -like "*.wsp*"}
Foreach ($wsp in $WSPList )
{
    $WSPFullFileName = $wsp.FullName
    $WSPFileName = $wsp.Name
    clear
    Write-Host -ForegroundColor White -BackgroundColor Blue "Working on $WSPFileName"
 
    try
    {
        Write-Host -ForegroundColor Green "Checking Status of Solution"
        $output = Get-SPSolution -Identity $WSPFileName -ErrorAction Stop
    }
    Catch
    {
        $DoesSolutionExists = $_
    }
    If (($DoesSolutionExists -like "*Cannot find an SPSolution*") -and ($output.Name -notlike  "*$WSPFileName*"))
    {
        Try
        {
            Write-Host -ForegroundColor Green "Adding solution to farm"
            Add-SPSolution "$WSPFullFileName" -Confirm:$false -ErrorAction Stop | Out-Null
 
            Write-Host -ForegroundColor Green "Checking Status of Solution"
            $output = Get-SPSolution -Identity $WSPFileName -ErrorAction Stop
            $gobal = $null
            if ($output.Deployed -eq $false)
            {
                try
                {
                    Write-Host -ForegroundColor Green "Deploy solution to all Web Apps, will skip if this solution is globally deployed"
                    Install-SPSolution -Identity "$WSPFileName" -GACDeployment -AllWebApplications -Force -Confirm:$false -ErrorAction Stop | Out-Null
                }
                Catch
                {
                    $gobal = $_
                }
                If ($gobal -like "*This solution contains*")
                {
                    Write-Host -ForegroundColor Green "Solution requires global deployment, Deploying now"
                    Install-SPSolution -Identity "$WSPFileName" -GACDeployment -Force -Confirm:$false -ErrorAction Stop | Out-Null
                }
            }
 
            Sleep 1
            $dpjobs = Get-SPTimerJob | Where { $_.Name -like "*$WSPFileName*" }
            If ($dpjobs -eq $null)
            {
                Write-Host -ForegroundColor Green "No solution deployment jobs found"
            }
            Else
            {
                If ($dpjobs -is [Array])
                {
                    Foreach ($job in $dpjobs)
                    {
                        $jobName = $job.Name
                        While ((Get-SPTimerJob $jobName -Debug:$false) -ne $null)
                        {
                            Write-Host -ForegroundColor Yellow -NoNewLine "."
                            Start-Sleep -Seconds 5
                        }
                        Write-Host
                    }
                }
                Else
                {
                    $jobName = $dpjobs.Name
                    While ((Get-SPTimerJob $jobName -Debug:$false) -ne $null)
                    {
                        Write-Host -ForegroundColor Yellow -NoNewLine "."
                        Start-Sleep -Seconds 5
                    }
                    Write-Host
                }
            }
        }
        Catch
        {
            Write-Error $_
            Write-Host -ForegroundColor Red "Skipping $WSPFileName, Due to an error"
            Read-Host
        }
    }
    Else
    {
        $skip = $null
        $tryagain = $null
        Try
        {
            if ($output.Deployed -eq $true)
            {
            Write-Host -ForegroundColor Green "Retracting Solution"
            Uninstall-SPSolution -AllWebApplications -Identity $WSPFileName -Confirm:$false -ErrorAction Stop
            }
        }
        Catch
        {
            $tryagain = $_
        }
        Try
        {
            if ($tryagain -ne $null)
            {
                Uninstall-SPSolution -Identity $WSPFileName -Confirm:$false -ErrorAction Stop
            }
        }
        Catch
        {
            Write-Host -ForegroundColor Red "Could not Retract Solution"
        }
 
        Sleep 1
        $dpjobs = Get-SPTimerJob | Where { $_.Name -like "*$WSPFileName*" }
        If ($dpjobs -eq $null)
        {
            Write-Host -ForegroundColor Green "No solution deployment jobs found"
        }
        Else
        {
            If ($dpjobs -is [Array])
            {
                Foreach ($job in $dpjobs)
                {
                    $jobName = $job.Name
                    While ((Get-SPTimerJob $jobName -Debug:$false) -ne $null)
                    {
                        Write-Host -ForegroundColor Yellow -NoNewLine "."
                        Start-Sleep -Seconds 5
                    }
                    Write-Host
                }
            }
            Else
            {
                $jobName = $dpjobs.Name
                While ((Get-SPTimerJob $jobName -Debug:$false) -ne $null)
                {
                    Write-Host -ForegroundColor Yellow -NoNewLine "."
                    Start-Sleep -Seconds 5
                }
                Write-Host
            }
        }       
 
        Try
        {
            Write-Host -ForegroundColor Green "Removing Solution from farm"
            Remove-SPSolution -Identity $WSPFileName -Confirm:$false -ErrorAction Stop
        }
        Catch
        {
            $skip = $_
            Write-Host -ForegroundColor Red "Could not Remove Solution"
            Read-Host
        }
        if ($skip -eq $null)
        {
            Try
            {
                Write-Host -ForegroundColor Green "Adding solution to farm"
                Add-SPSolution "$WSPFullFileName" -Confirm:$false -ErrorAction Stop | Out-Null
                $gobal = $null
                try
                {
                    Write-Host -ForegroundColor Green "Deploy solution to all Web Apps, will skip if this solution is globally deployed"
                    Install-SPSolution -Identity "$WSPFileName" -GACDeployment -AllWebApplications -Force -Confirm:$false -ErrorAction Stop | Out-Null
                }
                Catch
                {
                    $gobal = $_
                }
                If ($gobal -like "*This solution contains*")
                {
                    Write-Host -ForegroundColor Green "Solution requires global deployment, Deploying now"
                    Install-SPSolution -Identity "$WSPFileName" -GACDeployment -Force -Confirm:$false -ErrorAction Stop | Out-Null
                }
            }
            Catch
            {
                Write-Error $_
                Write-Host -ForegroundColor Red "Skipping $WSPFileName, Due to an error"
                Read-Host
            }
 
            Sleep 1
            $dpjobs = Get-SPTimerJob | Where { $_.Name -like "*$WSPFileName*" }
            If ($dpjobs -eq $null)
            {
                Write-Host -ForegroundColor Green "No solution deployment jobs found"
            }
            Else
            {
                If ($dpjobs -is [Array])
                {
                    Foreach ($job in $dpjobs)
                    {
                        $jobName = $job.Name
                        While ((Get-SPTimerJob $jobName -Debug:$false) -ne $null)
                        {
                            Write-Host -ForegroundColor Yellow -NoNewLine "."
                            Start-Sleep -Seconds 5
                        }
                        Write-Host
                    }
                }
                Else
                {
                    $jobName = $dpjobs.Name
                    While ((Get-SPTimerJob $jobName -Debug:$false) -ne $null)
                    {
                        Write-Host -ForegroundColor Yellow -NoNewLine "."
                        Start-Sleep -Seconds 5
                    }
                    Write-Host
                }
            }
    }
    Else
    {
        Write-Host -ForegroundColor Red "Cannot Install $WSPFileName, Please try manually"
        Read-Host
    }
}
}

How to get absolute URLs in SharePoint

Use the SPSite.MakeFullUrl() function:

public string MakeFullUrl(
string strUrl
)
Simply pass in the string of the relative URL and it returns you the absolute URL.
For example:
string imageUrl = site.MakeFullUrl("/_layouts/images/siteIcon.png"); 

Saturday, October 20, 2012

Restore Site BackUp Using Powershell

Add-PsSnapin Microsoft.SharePoint.Powershell –ErrorAction SilentlyContinue

      Write-Host  
      Write-Host  
      Write-Host "Backup starting at $backupStart for $Site "  
      Write-Host "******************************************"
     Restore-SPSite -Identity http://globas:1040/ -Path "E:\Sharepoint\FirstPrincipal\SiteBackUp\FPBakup\Latest\fp_04oct2012-latest.bak" -force   
   
      Write-Host  
      Write-Host  
      Write-Host "Backup Completed at $backupComplete for $Site "  
      Write-Host "******************************************"

Write-Host "Finished! Press enter key to exit." -ForegroundColor Green
Read-Host

Save Site Template using Powershell

Add-PsSnapin Microsoft.SharePoint.Powershell –ErrorAction SilentlyContinue
$Web=Get-SPWeb http://globas/

$Web.SaveAsTemplate("test4","test4","test4",0)


Write-Host "Finished! Press enter key to exit." -ForegroundColor Green
Read-Host

Remove Web Application using Powershell


Add-PsSnapin Microsoft.SharePoint.Powershell –ErrorAction SilentlyContinue
Remove-SPWebApplication http://globas:1030 -Confirm -DeleteIISSite -RemoveContentDatabases

Remove Solution using Powershell

Add-PsSnapin Microsoft.SharePoint.Powershell –ErrorAction SilentlyContinue

 

Uninstall-SPSolution –Identity readmorewsp.wsp  -force

Write-Host "Finished! Press enter key to exit." -ForegroundColor Green
Start-Sleep -Seconds 30

Remove-SPSolution –Identity readmorewsp.wsp -force

Write-Host "Finished! Press enter key to exit." -ForegroundColor Green
Start-Sleep -Seconds 5

Uninstall-SPSolution –Identity fpmasterpage .wsp  -force

Write-Host "Finished! Press enter key to exit." -ForegroundColor Green
Start-Sleep -Seconds 30

Remove-SPSolution –Identity fpmasterpage .wsp -force

Write-Host "Finished! Press enter key to exit." -ForegroundColor Green

 

Write-Host "Finished! Press enter key to exit." -ForegroundColor Green
Read-Host

New Site And Templates Using Powershell

Add-PsSnapin Microsoft.SharePoint.Powershell –ErrorAction SilentlyContinue

 

      Write-Host  
      Write-Host  
      Write-Host "Creating New Site....  "  

 

 

$newSite = New-SPWeb -URL "http://globas:1030" -Template "STS#1" -Name "Home"


$siteURL = $newSite

$owner = “Administrator”

$secondOwner = “Administrator”

$template = “STS#1?

$description = “This is a sample site that was built using PowerShell.”

New-SPSite $siteURL -OwnerAlias $owner -SecondaryOwnerAlias $secondOwner -name “PowerShell for SharePoint” -Template $template -Description $description

List All Web Application Lists using Powershell


Add-PsSnapin Microsoft.SharePoint.Powershell –ErrorAction SilentlyContinue
Get-SPWebApplication

Export List Data using Powershell

Add-PsSnapin Microsoft.SharePoint.Powershell –ErrorAction SilentlyContinue

$MyWeb = Get-SPWeb "http://Globas"
$MyList = $MyWeb.Lists["sample"]
$exportlist = @()
$Mylist.Items | foreach {
$obj = New-Object PSObject -Property @{
            “Column1” = $_["Body"]
                          
}
$exportlist += $obj
$exportlist | Export-Csv -path 'C:\dom.csv'
}

Enable Site Features using Powershell

Add-PsSnapin Microsoft.SharePoint.Powershell –ErrorAction SilentlyContinue

Enable-SPFeature "SharePoint Server Standard Site features" -Url http://globas:1050

Delete Particular Subsite using Powershell

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction "SilentlyContinue"

$ParentSiteUrl = "http://globas:1050/"

function DeleteSubSite([string]$SiteUrlName)
{
$SiteUrlName = $ParentSiteUrl + $SiteUrlName
Write-Host "SiteUrlName:" $SiteUrlName

Remove-SPWeb $SiteUrlName -Confirm:$false
Write-Host "Web:" $SubWeb.Title " deleted!"
}


DeleteSubSite "sun"

rm function:/DeleteSubSite

Write-Host "Finished! Press enter key to exit." -ForegroundColor Green
Read-Host

Delete List using Powershell

Add-PsSnapin Microsoft.SharePoint.Powershell –ErrorAction SilentlyContinue
$web = Get-SPWeb http://globas:1010
$custom = $web.lists["Articles"]
$custom.Delete()

$custom1 = $web.lists["BasicWebparts - Gallery"]
$custom1.Delete()

$custom2 = $web.lists["ContentSlides"]
$custom2.Delete()

$custom3 = $web.lists["domphoto"]
$custom3.Delete()

$custom4 = $web.lists["dp"]
$custom4.Delete()

$custom5 = $web.lists["gallery"]
$custom5.Delete()

$custom6 = $web.lists["photo1"]
$custom6.Delete()

 

 

 

 


Write-Host "Finished! Press enter key to exit." -ForegroundColor Green
Read-Host

Create Subsite using Powershell


Add-PsSnapin Microsoft.SharePoint.Powershell –ErrorAction SilentlyContinue

New-SPWeb http://globas:1060/test -Template "STS#1"  -Name "test"

 

 

Write-Host "Finished! Press enter key to exit." -ForegroundColor Green
Read-Host

Daily Site Backup Powershell

Add-PsSnapin Microsoft.SharePoint.Powershell –ErrorAction SilentlyContinue
try
{
    $today = (Get-Date -Format dd-MM-yyyy)
    $backupDirectory = "D:\Backup\DailySiteCollectionBackUp\$today"
  # Backup file Location
    $backupFile = "D:\Backup\DailySiteCollectionBackUp\$today\Backup.bak"
  # Log file location
    $logFile = "$backupDirectory\BackupLog.log"  
  # Address of the Site Collection to backup
    $Site = "http://globas:1060/"
  
# Location of the Backup Folder
    if (-not (Test-Path $backupDirectory))
    {
      [IO.Directory]::CreateDirectory($backupDirectory)
      #New-Item $logPath -type $backupDirectory
    }
 
# Get backup start date and time
    $backupStart = Get-Date -format "MM-dd-yyyy HH.mm.ss"
  
  # creates a log file  Start-Transcript -Path
    Start-Transcript -Path $logFile
    
# This will actually initiate the backup process.
      Write-Host  
      Write-Host  
      Write-Host "Backup starting at $backupStart for $Site "  
      Write-Host "******************************************"
     Backup-SPSite -Identity $Site -Path $backupFile -Force
     $backupComplete = Get-Date -format "MM-dd-yyyy HH.mm.ss"
      Write-Host  
      Write-Host  
      Write-Host "Backup Completed at $backupComplete for $Site "  
      Write-Host "******************************************"
 
Stop-Transcript
}
Catch
{
  $ErrorMessage = $_.Exception.Message
  write "$today BackUp Failed   $ErrorMessage  ">>$logFile
 
}

Create Site Collection Using Powershell

Add-PsSnapin Microsoft.SharePoint.Powershell –ErrorAction SilentlyContinue


#Get-SPWebApplication


     # Remove-SPWebApplication http://globas:1050 -Confirm -DeleteIISSite -RemoveContentDatabases

#Write-Host "Finished! Press enter key to exit." -ForegroundColor Green
#Read-Host


function Start-SiteCollectionCreate(
    [string]$settingsFile = "sites.xml") {
    [xml]$config = Get-Content $settingsFile
   
    $config.SiteCollections.SiteCollection | ForEach-Object {

 

#Create WebApplication
Write-Host  
      Write-Host  
      Write-Host "WebApplication Creating........"  
      Write-Host "******************************************"
New-SPWebApplication -Name $_.Name -Port $_.Port -AllowAnonymousAccess  -URL $_.SiteCreationUrl -ApplicationPool $_.Pool -ApplicationPoolAccount (Get-SPManagedAccount $_.OwnerLogin)

Write-Host  
      Write-Host  
      Write-Host "WebApplication Sucussfully Created........" 

 

 


Write-Host  
      Write-Host  
      Write-Host "Site collection Creating........"  
      Write-Host "******************************************"


        #Creating site collection
        Write-Host "Creating site collection $($_.Url)..."
        $gc = Start-SPAssignment
        $site = $gc | New-SPSite `
            -Url $_.Url `
            -Description $_.Description `
            -Language $_.LCID `
            -Name $_.Name `
            -Template $_.Template `
            -OwnerAlias $_.OwnerLogin `
            -OwnerEmail $_.OwnerEmail `
            -SecondaryOwnerAlias $_.SecondaryLogin `
            -SecondaryEmail $_.SecondaryEmail
            Stop-SPAssignment -SemiGlobal $gc
        # Associate Default Groups (Dan Holme: http://www.sharepointpromag.com/article/sharepoint/Create-a-SharePoint-Site-Collection-with-Windows-PowerShell-UI-Style)
        $MembersGroup = "$_.Name Members"
        $ViewersGroup = "Viewers"
        $web = Get-SPWeb $_.url
        $web.CreateDefaultAssociatedGroups($_.OwnerLogin,$_.SecondaryLogin,"")
        $PrimaryAdmin = Get-SPUser $_.OwnerLogin -Web $_.url
        $PrimaryAdmin.Name = $_.OwnerDisplay
        $PrimaryAdmin.Update()
        $SecondaryAdmin = Get-SPUser $_.SecondaryLogin -Web $_.url
        $SecondaryAdmin.Name = $_.SecondaryDisplay
        $SecondaryAdmin.Update()

        # Finish by disposing of the SPWeb object to be a good PowerShell citizen
        $web.Dispose()
        }
    }

# Execute the script           
Start-SiteCollectionCreate


Write-Host  
      Write-Host  
      Write-Host "Site Collection Created........"  


Write-Host "Finished! Press enter key to exit." -ForegroundColor Green
Read-Host

 


 

Xml File

 

<SiteCollections>                   
    <SiteCollection Name="globas-1020"
                    Description=""
                    SiteCreationUrl="http://globas:1020/"
                    Port="1020"
                    Pool="globas1020"
                    Url="http://globas:1020"
                    LCID="1033"
                    Template="STS#0"
                    OwnerLogin="glob\administrator"
                    OwnerEmail="administrator@sgs.com"
                    OwnerDisplay="Administrator"
                    SecondaryLogin="glob\administrator"
                    SecondaryEmail="admin@cdfdontoso.com"
                    SecondaryDisplay="SharePoint Farm">
    </SiteCollection>

 

</SiteCollections>