Archive

Archive for the ‘PowerShell’ Category

How to write PowerShell code part 4 (using loop)

May 31, 2013 Leave a comment

In this post, I’d like to show you how to loop through the xml element. I will use the list data deletion script as an example. You can download the script here.

1. To perform the loop, I use foreach in powershell. Here is my xml looks like


<?xml version="1.0" encoding="utf-8"?>
<Site Url="http://workflowuat/npdmoc">
 <Lists>
 <List Name="YBBEST Collaboration Areas" Type="Document Library"/>
 <List Name="YBBEST Project" />
 <List Name="YBBEST Document"/>
 </Lists>
</Site>

2. Here is the PowerShell to manipulate the xml. Note, you need to get to the $configurationXml.Site.Lists.List variable rather than $configurationXml.Site.Lists


foreach ($list in $configurationXml.Site.Lists.List){
 AppendLog "Clearing data for $($list.Name) at site $weburl" Yellow
 if($list.Type -eq "Document Library"){
 deleteItemsFromDocumentLibrary -Url $weburl -ListName $list.Name
 }else{
 deleteItemsFromList -Url $weburl -ListName $list.Name
 }
 AppendLog "Data in $($list.Name) at $weburl is cleared" Green
}

How to write PowerShell code part 1
How to write PowerShell code part 2
How to write PowerShell code part 3
How to write PowerShell code part 4

Advertisements

How to fix “Microsoft SharePoint is not supported with version 4.0.30319.225 of the Microsoft .Net Runtime” in PowerGUI

July 14, 2012 6 comments

Today, when I try to run some PowerShell command against SharePoint in PowerGUI , I encounter some error message as below:

Problem:

Remove-SPSite : Microsoft SharePoint is not supported with version 4.0.30319.225 of the Microsoft .Net Runtime.

At C:\SiteCreation.ps1:37 char:14

+ CategoryInfo : InvalidData: (Microsoft.Share…mdletRemoveSite:SPCmdletRemoveSite) [Remove-SPSite], PlatformNotSupportedException

Analysis:

The error message is pretty clear that PowerGUI try to run the PowerShell command under .Net version 4.0 which is not supported by SharePoint2010, SharePoint2010 only support .Net 3.5.So how can I change the settings so that PowerShell does run under .Net3.5 in PowerGui? The solution is pretty easy.

Solution:

1. Open your windows explorer and navigate to C:\Program Files (x86)\PowerGUI\ and open the configuration file ScriptEditor.exe.config.

2. Change the supportedRuntime version under Startup settings by removing the version=”v4.0″ as below

From


To


 

3. Restart your PowerGUI and rerun your script. It works like a charm.

How to write PowerShell code part 2 (Using function)

May 13, 2012 Leave a comment

In the last post, I have showed you how to use external configuration file in your PowerShell script. In this post, I will show you how to create PowerShell function and call external PowerShell script.You can download the script here.

1. In the original script, I create the site directly using New-SPSite command. I will refactor it so that I will create a new function to create the site using New-SPSite. The PowerShell function is quite similar to a C# method. You put your function parameters in () and separate each parameter by a comma (,). Then you put your method body in {}.

function add ([int] $num1 , [int] $num2){
$total=$num1+$num2
#Return $total
$total
}

2. The difference is you do not need semi-colon (;) at the end of each statement and when calling the method you do not need comma (,) to separate each parameter.

function add ([int] $num1 , [int] $num2){
$total=$num1+$num2

#Return $total
$total
}

#Calling the function
[int] $num1=3
[int] $num2=4
$d= add $num1 $num2
Write-Host $d

3. If you like to return anything from the function, you just need to type in the object you like to return, not need to type return .e.g. $ObjectToReturn not return $ObjectToReturn

 

How to write PowerShell code part 1
How to write PowerShell code part 2
How to write PowerShell code part 3
How to write PowerShell code part 4

Categories: PowerShell Tags:

How to write PowerShell code part 1 (Using external xml configuration file)

May 13, 2012 1 comment

In this post, I will show you how to use external xml file with PowerShell. The advantage for doing so is that you can avoid other people to open up your PowerShell code to make the configuration changes; instead all they need to do is to change the xml file. I will refactor my site creation script as an example; you can download the script here and refactored code here.

1. As you can see below, I hard code all the variables in the script itself.


$url = "http://ybbest"
$WebsiteName = "Ybbest"
$WebsiteDesc = "Ybbest test site"
$Template = "STS#0"
$PrimaryLogin = "contoso\administrator"
$PrimaryDisplay = "administrator"
$PrimaryEmail = "administrator@contoso.com"
$MembersGroup = "$WebsiteName Members"
$ViewersGroup = "$WebsiteName Viewers"

2. Next, I will show you how to manipulate xml file using PowerShell. You can use the get-content to grab the content of the file.

[xml] $xmlconfigurations=get-content .\SiteCollection.xml

3. Then you can set it to variable (the variable has to be typed [xml] after that you can read the content of the xml content, PowerShell also give you nice IntelliSense by press the Tab key.

[xml] $xmlconfigurations=get-content .\SiteCollection.xml
$xmlconfigurations.SiteCollection
$xmlconfigurations.SiteCollection.SiteName

4. After refactoring my code, I can set the variables using the xml file as below.


#Set the parameters
$siteInformation=$xmlinput.SiteCollection
$url = $siteInformation.URL
$siteName = $siteInformation.SiteName
$siteDesc = $siteInformation.SiteDescription
$Template = $siteInformation.SiteTemplate
$PrimaryLogin = $siteInformation.PrimaryLogin
$PrimaryDisplay = $siteInformation.PrimaryDisplayName
$PrimaryEmail = $siteInformation.PrimaryLoginEmail
$MembersGroup = "$WebsiteName Members"
$ViewersGroup = "$WebsiteName Viewers"

How to write PowerShell code part 1
How to write PowerShell code part 2
How to write PowerShell code part 3
How to write PowerShell code part 4

How to fix “Unable to cast COM object of type ‘Microsoft.SharePoint.Library.SPRequestInternalClass’ to interface type ‘Microsoft.SharePoint.Library.ISPRequest” using PowerGUI

March 20, 2012 4 comments

I got the error today when debugging some of my PowerShell Script in PowerGUI. The script works perfectly fine in PowerShell console. Then I had spent a couple of hours scratching my head, trying to figure out why. It turns out that the PowerShell Variables Panel causes the problem. Not quite sure why, but collapse the panel fix the problem.

Problem:

It throws the following exception when debugging my PowerShell Script.

Analysis:

It turns out that the PowerShell Variables Panel causes the problem. I assume it calls some function to grab value of some of variables which cause the problems.


Solution:

Collapse or Close the variables panel fix the problem

How to create a folder in SharePoint2010 root folder and set permission to it

March 14, 2012 Leave a comment

If you need to create a folder in SharePoint2010 root folder and set permission to it, here is piece of code that does it. In the script, I have created a folder called Temp in Logs folder under SharePoint2010 root and then I grant read/write access to the Windows group WSS_WPG and full access to the group WSS_ADMIN_WPG for that folder.

$Folder=New-Item "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\LOGS\temp" -Type Directory -force
$acl = Get-Acl $Folder
##The following line has been commented out , if you like to break the permission inheritance from the parent floder , uncommented the code.
#$acl.SetAccessRuleProtection($True, $False)
$rule = New-Object System.Security.AccessControl.FileSystemAccessRule("WSS_ADMIN_WPG","FullControl", "ContainerInherit, ObjectInherit", "None", "Allow")
$acl.AddAccessRule($rule)
$rule = New-Object System.Security.AccessControl.FileSystemAccessRule("WSS_WPG","Modify", "ContainerInherit, ObjectInherit", "None", "Allow") 
$acl.AddAccessRule($rule)
Set-Acl $Folder $acl

References:

http://technet.microsoft.com/en-us/library/ff730951.aspx

http://msdn.microsoft.com/en-us/library/tbsb79h3.aspx

http://blogs.technet.com/b/josebda/archive/2010/11/12/how-to-handle-ntfs-folder-permissions-security-descriptors-and-acls-in-powershell.aspx

http://chrisfederico.wordpress.com/2008/02/01/setting-acl-on-a-file-or-directory-in-powershell/

 

 

 

Categories: PowerShell Tags:

How to add configuration settings using SPWebConfigModification and PowerShell Script

February 28, 2012 2 comments

In recent project, I need to store SMTP configurations in the web.config. In this post I’d like to show you how to update the web.config using SPWebConfigModification and PowerShell Script.

#add configuration settings using SPWebConfigModification and PowerShell Script
#
#param( [Parameter(Mandatory=$true, ValueFromPipeline=$true, Position=0)]
#			[Microsoft.SharePoint.PowerShell.SPWebApplicationPipeBind]
#			$WebApplication)
param( [string]$webApplicationUrl,[string]$smtpServerName,[string]$smtpServerPort,[string]$owner)
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

function AddConfigModification
{    param ([Microsoft.SharePoint.Administration.SPWebConfigModification]$ConfigMod,$WebApp)
	if($WebApp.WebConfigModifications.Contains($ConfigMod)){
        $WebApp.WebConfigModifications.Remove($ConfigMod)
	}
		$WebApp.WebConfigModifications.Add($ConfigMod)
}

function NewWebConfigModification
{
	param ([string]$keyName,$sequence,[string]$owner,[string]$value)
    $webMod =  New-Object Microsoft.SharePoint.Administration.SPWebConfigModification
    $webMod.Path = "configuration/appSettings"
    $webMod.Name = [string]::Format("add[@key='{0}']", $keyName)
    $webMod.Sequence = $sequence
    ## SPWebConfigModificationType.EnsureChildNode -> 0
	## SPWebConfigModificationType.EnsureAttribute -> 1
	## SPWebConfigModificationType.EnsureSection -> 2
    $webMod.Type = 0
    $webMod.Owner = $owner;
    $webMod.Value = $value
	$webMod
}

if([Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")-eq $null){throw "Unable to load Microsoft.SharePoint.dll";}
$WebApp=Get-SPWebApplication -Identity $webApplicationUrl
$smtpServerNameKeyName="smtpServerName"
$smtpServerNameValue=''
$sequence=0
$smtpServerPortKeyName="smtpServerPort"
$smtpServerPortValue=''
$sequence=0
$smtpServerNameConfigMod = NewWebConfigModification $smtpServerNameKeyName $sequence $owner  $smtpServerNameValue
$smtpServerPortConfigMod = NewWebConfigModification $smtpServerPortKeyName $sequence $owner  $smtpServerPortValue
AddConfigModification $smtpServerNameConfigMod $WebApp
AddConfigModification $smtpServerPortConfigMod $WebApp
$WebApp.Update()
$WebApp.Parent.ApplyWebConfigModifications()

You can download the powershell code here.If you run the code and experience the following exception , you need to recreate your web application , it should solve the problem.

Exception calling “ApplyWebConfigModifications” with “0” argument(s): “Object reference not set to an instance of an object.”

*********Update 8 May 2012********

I have updated my code samples so that it will read from a XML for the configuration setting.You can download it from here.

References:

Modifying your Web.config file using SPWebConfigModifications

http://gavinb.net/2011/06/13/disable-mobile-redirection-for-a-web-application-via-powershell/

How to Create an Object in PowerShell