Affichage des articles dont le libellé est powershell. Afficher tous les articles
Affichage des articles dont le libellé est powershell. Afficher tous les articles

mardi 13 septembre 2011

Run powershell with elevated privileges

Sometimes,it depends on what you need to do, but you'll need to run power shell with elevated privileges.

You can run power shell with elevated privileges with this command line:
runas /noprofile /user:YOURUSER "C:\windows\system32\windowspowershell\v1.0\powershell.exe -NoExit & 'c:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\CONFIG\POWERSHELL\Registration\SharePoint.ps1

Add custom webpart to a page using power shell

In one of my client, I had to import a webpart in the webpart gallery and add this webpart to the welcome page using Power Shell.
Here is the script I've made.Hope this will help.

if((Get-PSSnapin "Microsoft.SharePoint.PowerShell" ) -eq $null)
{
Add-PSSnapin "Microsoft.SharePoint.PowerShell"
}

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Publishing")
[System.Reflection.Assembly]::LoadWithPartialName("System")

$site = new-object Microsoft.SharePoint.SPSite("http://mysite");
$web = $site.OpenWeb()
$fileDWP = $saveFolder + "myCustom.dwp"
$errorMsg = ""

[Microsoft.SharePoint.SPList]$wpList = $site.GetCatalog([Microsoft.SharePoint.SPListTemplateType]::WebPartCatalog)
$fileStream = ([System.IO.FileInfo](Get-Item $fileDWP)).OpenRead()

[Microsoft.SharePoint.SPFolder]$wpFolder = $wpList.RootFolder
[Microsoft.SharePoint.SPFile]$wpFile = $wpFolder.Files.Add("myCustom.webpart", $fileStream, $true)

$wpFile.Update();

[System.Xml.XmlReader]$xmlReader = [System.Xml.XmlReader]::Create($wpFile.OpenBinaryStream())
[Microsoft.SharePoint.Publishing.PublishingWeb]$pubWeb = [Microsoft.SharePoint.Publishing.PublishingWeb]::GetPublishingWeb($web);
[Microsoft.SharePoint.SPFile]$defaultPage = $pubWeb.DefaultPage;
[Microsoft.SharePoint.WebPartPages.SPLimitedWebPartManager]$wpManager = $defaultPage.GetLimitedWebPartManager([System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)

$myCustomWP = $wpManager.ImportWebPart($xmlReader,[ref]$errorMsg)
$wpManager.AddWebPart($infoWp, "Right", 1);
$fileSream.Close()
$xmlReader.Close()
$pubWeb.Close()
$web.Dispose()
$site.Dispose()

write-host "Done"