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

Friday, February 3, 2017

Remove App from SharePoint Online with Powershell

Hi,

Today I was facing some issues in installed custom app. I was not able to get App Details & also not able to remove the app. I tried alot from interface but I couldn't remove the app. Then I move to Powershell scripts.

Here is the powershell script which can remove the app from SharePoint Online. Only prerequisite is you must have SharePoint Online Client Components SDK installed on the system.

cls
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client")
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.Runtime")


Function Get-ClientContext([string]$Url,[string]$UserName,[string]$Password)
{
    $context = New-Object Microsoft.SharePoint.Client.ClientContext($Url)
    $context.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($UserName, $Password)
    return $context
}


Function Uninstall-AppInstance([Microsoft.SharePoint.Client.ClientContext]$Context,[Guid]$AppInstanceId)
{
    $appInst = $Context.Web.GetAppInstanceById($AppInstanceId)
    $appInst.Uninstall()
    $context.ExecuteQuery()
 }




$UserName = "gaurav.goyal@myorgs.com"
$Password=Read-Host -Prompt "Password" -AsSecureString;

$Url = "https://mytenant.sharepoint.com"
$AppInstanceid = New-Object Guid("XXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX")  #you need to specify App Instance Id here

$context = Get-ClientContext -Url $Url -UserName $UserName -Password $Password

Uninstall-AppInstance -Context $context -AppInstanceId $AppInstanceid
$context.Dispose()

Wednesday, November 2, 2016

Publish files which are not published by users

#Set-ExecutionPolicy Unrestricted
#Set-ExecutionPolicy RemoteSigned
cls

$Host.UI.RawUI.WindowTitle = "-- Publish Files --"

$scriptdir = $PSScriptRoot


#$DatePrefix ="XML\"+ (Get-Date).ToString("MMddyyyyHHmm")
$DatePrefix ="XML\"

Write-Host "Loading the CSOM library" -foregroundcolor yellow

Add-Type -AssemblyName System.Web
# Paths to SDK. Please verify location on your c omputer.
Add-Type -Path "$scriptdir\Microsoft.SharePoint.Client.dll"
Add-Type -Path "$scriptdir\Microsoft.SharePoint.Client.Runtime.dll"
Add-Type -Path "$scriptdir\Microsoft.SharePoint.Client.Publishing.dll"
Add-Type -Path "$scriptdir\Microsoft.SharePoint.Client.Taxonomy.dll"
Write-Host "Succesfully loaded the CSOM library" -foregroundcolor green

# Insert the credentials and the name of the admin site
$Username="gaurav@goyal.com";
$AdminPassword=Read-Host -Prompt "Password" -AsSecureString;

$AdminUrl="<<Your Site Collection URL"


$StyleLibrary="Style Library"
$MasterPage="Master Page Gallery"

Write-Host "Connecting to site" -foregroundcolor yellow
   
$ctx=New-Object Microsoft.SharePoint.Client.ClientContext($AdminUrl)
$ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Username, $AdminPassword)



Function getUnPublishedFiles($listName){

    Write-Host ""
    Write-Host ""
    Write-Host ""
    Write-Host "Working on $listName....." -ForegroundColor Gray


    Write-Host "Creating file $listName.txt" -foregroundcolor yellow
    $xmlFilePath = "$scriptdir\XML\$listName.txt"

    #Create Export Files
    New-Item $xmlFilePath -type file -force

    #Managed Client Object Model CAML Query Syntax
    $spList = $ctx.Web.Lists.GetByTitle($listName);
    $localWeb=$ctx.Web;
    $ctx.Load($spList);
    $ctx.Load($localWeb);
    $ctx.ExecuteQuery();

    if ($spList -ne $null -and $spList.ItemCount -gt 0)
    {
       #$camlQuery = New-Object Microsoft.SharePoint.Client.CamlQuery()
       $camlQuery =[Microsoft.SharePoint.Client.CamlQuery]::CreateAllItemsQuery(1000);

       $camlQuery.ViewXml = "<View Scope='RecursiveAll'>"+
                                  "<Query>"+
                                     "<OrderBy>"+
                                        "<FieldRef Name='FileRef' />"+
                                        "</OrderBy>"+
                                    "<Where>"+
                                      "<Neq>"+
                                        "<FieldRef Name='_ModerationStatus' />"+
                                        "<Value Type='ModStat'>0</Value>"+
                                      "</Neq>"+
                                    "</Where>"+
                                  "</Query>"+
                                  "<ViewFields>"+
                                    "<FieldRef Name='FileLeafRef' />"+
                                    "<FieldRef Name='FileRef' />"+
                                    "<FieldRef Name='_ModerationStatus' />"+
                                  "</ViewFields>"+
                                "</View>";

       $listItems = $spList.GetItems($camlQuery);
       $ctx.Load($listItems);
       $ctx.ExecuteQuery()
       foreach($item in $listItems)
       {  
            $fileURL=$item["FileRef"].ToString()
            Write-Host $fileURL
            Add-Content $xmlFilePath $fileURL
           
            $newFile = $localWeb.GetFileByServerRelativeUrl($fileURL);
            $newFileItem = $newFile.ListItemAllFields;
            $ctx.Load($newFile);
            $ctx.Load($newFileItem);
            $ctx.ExecuteQuery();

            $newFile.Publish('Auto publsieh');
       }

       Invoke-Item "$scriptdir\XML\$listName.txt"
    }
}


getUnPublishedFiles($StyleLibrary)
getUnPublishedFiles($MasterPage)

Invoke-Item "$scriptdir\XML\"

Remove Deleted Site Collections from SharePoint Online

Cls

Write-Host "Remove Deleted Site Collections"
Write-Host "Password Please :"


#Set-ExecutionPolicy RemoteSigned


$username = "gaurav@goyal.com"
$password=Read-Host -Prompt "Password" -AsSecureString;


$siteAdminURL = "<<Main Tenent URL Here>>"


Import-Module Microsoft.Online.SharePoint.PowerShell –DisableNameChecking


#$securePassword = ConvertTo-SecureString $password –AsPlainText –force


$securePassword=$password


$O365Credential = New-Object System.Management.Automation.PsCredential($username, $securePassword)


Connect-SPOService -Url $siteAdminUrl -Credential $O365Credential

Get-SPODeletedSite | foreach {
Write-host "Deleting " $_.Url
Remove-SPODeletedSite –Identity $_.Url –Confirm:$false
}
Disconnect-SPOService
Write-Host "Removed Site Collections"

Thursday, December 4, 2014

Export ContentDataBase Name in csv file

<# Created by : Gaurav Goyal
   Purpose : To Export Content Database Name in csv file.
   Comments : Run With Admin Privileges \ Read operation.
#>

$csv="./CSV.csv"
$i=1;
SC $csv "ID,DBName,WebApplicationName,CurrentSiteCount"
write-host "`nGetting WebApplication Names`n";
$WebApps = Get-SPWebApplication 
foreach($WebAppUrl in $WebApps)
{
write-host "$i) Getting ContentDataBase name of WebApp" $WebAppUrl.Url "`n" ;$i++;
$toCSV=Get-SPContentDatabase -site $WebAppUrl.Url;
AC $csv "$($toCSV.Id),$($toCSV.Name),$($toCSV.WebApplication),$($toCSV.CurrentSiteCount)"
}
write-host "Exporting List of All DB.....`n"
Get-SPDatabase | epcsv ".\AllDataBaseList.csv"

Thursday, October 16, 2014

New Site Collection Through PowerShell

#Creates a SPSite in a new content database
Add-PSSnapin Microsoft.SharePoint.Powershell - ErrorAction SilentlyContinue;

$siteName = "IT";
$webAppUrl = "http://intranet2013.mydomain.com";
$template = "STS#0";

$ownerAlias = "mydomain\ggoyal";
$secondaryOwnerAlias = "mydomain\ggoyal";

$siteUrl = "$webAppUrl/sites/$siteName";
$databaseName = "SharePoint_Intranet_$siteName";
$databaseServer = "Test-Server";

New-SPContentDatabase -Name $databaseName -DatabaseServer $databaseServer -WebApplication $webAppUrl;

New-SPSite -Url $siteUrl -OwnerAlias $ownerAlias -SecondaryOwnerAlias $secondaryOwnerAlias -ContentDatabase $databaseName -Template $template -Name $siteName;

# New SPSite does not create the default groups

$web = Get-SPWeb $siteUrl;
$web.CreateDefaultAssociatedGroups("i:0#.w|$ownerAlias", "i:0#.w|$secondaryOwnerAlias", $siteName);
$web.update();

Saturday, March 1, 2014

Update Solution with Powershell

Add-PSSnapin Microsoft.SharePoint.Powershell -ErrorAction SilentlyContinue

$SolutionPackageName = "MySolution.wsp"
$SolutionPackagePath = "C:\PowershellSetup\MySolution.wsp"

Write-Host "Checking Solution exist or not..." -foregroundcolor Yellow
$solution = Get-SPSolution | where-object {$_.Name -eq $SolutionPackageName}
if($solution -ne $null)
{
Write-Host "Solution Found & Updating Solution..." -foregroundcolor Green
Update-SPSolution -Identity $SolutionPackageName -LiteralPath $SolutionPackagePath -Local -GACDeployment -Force
Write-Host "Solution Updated..." -foregroundcolor Yellow
}

Write-Host "Solution Updation Complete." -foregroundcolor Green

Install WSP with Powershell

Add-PSSnapin Microsoft.SharePoint.Powershell -ErrorAction SilentlyContinue

$SolutionPackageName = "MySolution.wsp"
$SolutionPackagePath = "C:\PowershellSetup\MySolution.wsp"

Write-Host "Checking Solution exist or not..." -foregroundcolor Yellow
$solution = Get-SPSolution | where-object {$_.Name -eq $SolutionPackageName}
if($solution -ne $null)
{
Write-Host "Solution Found..." -foregroundcolor Green
if($solution.Deployed -eq $true)
{
Write-Host "Uninstalling Solution..." -foregroundcolor red
Uninstall-SPSolution -Identity $SolutionPackageName -Local -Confirm:$false
Write-Host "Uninstallation Done..." -foregroundcolor Yellow
}
Write-Host "Removing Solution..." -foregroundcolor red
Remove-SPSolution -Identity $SolutionPackageName -Confirm:$false
Write-Host "Solution Removed..." -foregroundcolor Yellow
}

Write-Host "Adding Solution..." -foregroundcolor red
Add-SPSolution -LiteralPath $SolutionPackagePath
Write-Host "Solution Added..." -foregroundcolor Yellow

Write-Host "Installing Solution..." -foregroundcolor red
Install-SPSolution -Identity $SolutionPackageName -Local -GACDeployment -Force
Write-Host "Solution Installed..." -foregroundcolor Yellow
Write-Host "Deployment Complete." -foregroundcolor Green

Thursday, July 25, 2013

PowerShell Command to Export Sub Site


Export site with these option. This will include all customizations, user securities, list & libraries etc.

Export-SPWeb -Identity http://sharepoint-demo/IC -Path "c:\bkup\IC.cmp" -Force -IncludeUserSecurity -IncludeVersions All


Note :
·         http://sharepoint-demo/IC : You can change this site url. Put url of site which is going to be backed up.
·         C:\backup\IC.cmp : You can change backup path with file name. You have to keep extention .cmp as it is.




Tuesday, March 12, 2013

PowerShell Command to create new site collection


Create a Content Database

New-SPContentDatabase -Name IC_Content_DB -WebApplication http://sharepoint-demo


Note :
“IC_Content_DB” :- Name of new content database for new Site Collection
http://sharepoint-demo” :-  Name of Web Application where you want to create new site collection with the url http://sharepoint-demo/IC






Now create a site collection

$template = Get-SPWebTemplate "STS#0"
New-SPSite -Url "http://sharepoint-demo/IC" -OwnerAlias "sharepointdemo\gaurav" –ContentDatabase IC_Content_DB -Template $template



Administrator is not able to change user’s picture in User Profile in SharePoint Admin Center

For some users Admin is able to change picture by going to User Profile -> Manage user profile option. But for some users , Admin ...