Steps to Create Timer Job in SharePoint

  1. Steps to Create Timer Job

//Create class derived from SPJonDefinition Class

class ListTimerJob : SPJobDefinition

{

public ListTimerJob()

base()

{

}

public ListTimerJob(string jobName, SPService service, SPServer server, SPJobLockType targetType)

base(jobName, service, server, targetType)

{

}

public ListTimerJob(string jobName, SPWebApplication webApplication)

: base(jobName, webApplication, null, SPJobLockType.ContentDatabase)

{

this.Title = “List Timer Job”;

}

public override void Execute(Guid contentDbId)

{

// get a reference to the current site collection’s content database

SPWebApplication webApplication = this.Parent as SPWebApplication;

SPContentDatabase contentDb = webApplication.ContentDatabases[contentDbId];

// get a reference to the “ListTimerJob” list in the RootWeb of the first site collection in the content database

SPList Listjob = contentDb.Sites[0].RootWeb.Lists[“ListTimerJob”];

// create a new list Item, set the Title to the current day/time, and update the item

SPListItem newList = Listjob.Items.Add();

newList[“Title”] = DateTime.Now.ToString();

newList.Update();

}

}

//Add Event receiver at Feature Level

[Guid(“9a724fdb-e423-4232-9626-0cffc53fb74b”)]

public class Feature1EventReceiver : SPFeatureReceiver

{

const string List_JOB_NAME = “ListLogger”;

// Uncomment the method below to handle the event raised after a feature has been activated.

public override void FeatureActivated(SPFeatureReceiverProperties properties)

{

SPSite site = properties.Feature.Parent as SPSite;

// make sure the job isn’t already registered

foreach (SPJobDefinition job in site.WebApplication.JobDefinitions)

{

if (job.Name == List_JOB_NAME)

job.Delete();

}

// install the job

ListTimerJob listLoggerJob = new ListTimerJob(List_JOB_NAME, site.WebApplication);

SPMinuteSchedule schedule = new SPMinuteSchedule();

schedule.BeginSecond = 0;

schedule.EndSecond = 59;

schedule.Interval = 5;

listLoggerJob.Schedule = schedule;

listLoggerJob.Update();

}

// Uncomment the method below to handle the event raised before a feature is deactivated.

public override void FeatureDeactivating(SPFeatureReceiverProperties properties)

{

SPSite site = properties.Feature.Parent as SPSite;

// delete the job

foreach (SPJobDefinition job in site.WebApplication.JobDefinitions)

{

if (job.Name == List_JOB_NAME)

job.Delete();

}

}

  1. b.    Debug Timer Job: OWSTIMER.EXE
  2. OWSTIMER.EXE is the process executing Timer Jobs
  3. d.     View the Results
    1. Now we can go to the Central Administration to see our Timer Job.  For this open Central Administration web site and go to Monitoring > Review Job Definitions

 

  • On clicking the Review Job Definitions link you can see our item as shown below

  • Click on the item and in the appearing page click the button Run Now

 

  • You can see that the Timer Job is set for 5 Minutes according to our code.
Advertisements

How can we set own properties to profile manager?

How can we set own properties to profile manager?

using Microsoft.Office.Server;

using Microsoft.Office.Server.UserProfiles;

public static SPSite site = new SPSite(ConfigSettings.GetConfigAppSettings(“SiteURL”));

public static UserProfile UserInformation(string userAccountName)

{

ServerContext context = ServerContext.GetContext(site);

UserProfileManager profileManager = new UserProfileManager( context);

string sAccount = userAccountName;

UserProfile profile = null;

if (profileManager.UserExists(sAccount))

{

profile = profileManager.GetUserProfile(sAccount);

profile[PropertyConstants.HomePhone].Value = “”;

profile[PropertyConstants.FirstName].Value = “”;

profile.Commit();

}

return profile;

}

Impersonation in SharePoint

Impersonation in SharePoint

 

SharePoint security model makes it easy to programmatically execute code within the current user context.

Just write and deploy web part / event handler code and it runs in the security context of the logged in user. There are even built-in functions that take advantage of the user’s security context – such as GetSubwebsForCurrentUser() – without requiring any extra coding on our part which is simple yet effective security mechanism.

But there are situations when the code needs to be executed with permissions greater than that of the current user (like instantiating a site collection or enumerating list permissions or reading a lookup / configuration list on which user may not have access rights).

In such situations, the code needs to be executed with elevated permission level or under the context of user with higher permissions i.e. Impersonation.

So here are the two approaches for u —-

Executing code as another named user

Process

When we create a SharePoint site programmatically using the Microsoft.SharePoint namespace, we can supply a user token which enables you to create objects in the context of a specific user. You can impersonate a user by supplying the user token for that user, obtained from the Microsoft.SharePoint.SPUser object. The user token, SPUserToken, is a binary object that contains the identification and domain group membership of a user.

This allows you to use the Microsoft.SharePoint.SPSite constructor to instantiate a site collection object that runs as if that user was making changes.

SPSite site = new SPSite(“SiteCollection_Url”);

SPWeb web = site.OpenWeb();

SPUser user = web.AllUsers[“User_Name”];

SPUserToken token = user.UserToken;

SPSite impersonatedSiteCollection = new SPSite(“SiteCollection_Url”, token);

Any objects (SPWeb, SPList, etc) that you create from this impersonated site collection will execute as the impersonated user.

Where to Use –

This Approach is useful to run any code which requires specific permissions to execute that code (like permission for reading a particular list), rather than having a full control access permission.

In such a case, service account can be created by specific access rights just sufficient enough to execute the code.

Caution-

Although impersonation provides a powerful new technique for managing security, it should be used with care to make sure that unwanted activity is not performed by users who shouldn’t have the ability to impersonate.

Executing code with elevated privileges

Process

Method 1 –

Elevation of privilege is a new feature of that enables you to programmatically perform actions in code using an increased level of privilege. The Microsoft.SharePoint.SPSecurity.RunWithElevatedPrivileges method enables you to supply a delegate that runs a subset of code in the context of an account with higher privileges than the current user.

For example:

1. Define a public method that acts simply as a front end to the method that does the “real” work.

public void ProcessMethod()

{

SPSecurity.CodeToRunElevated elevatedMethod = new SPSecurity.CodeToRunElevated( ProcessMethodAsElevated);

SPSecurity.RunWithElevatedPrivileges(elevatedMethod);

}

The code uses a method from SPSecurity to indicate the name of the method that will run with Full Control(Basically using Application Pool Account).

In the first line, simply pass in the name of the method as the parameter. In the second line, you execute that method with elevated privileges.

2. Now create the method that does the real work. It is called by the first method (delegate), but executes with Full Control(under Application Pool Account):

private void ProcessMethodAsElevated()

{

//code goes here to do our work

}

Method 2 –

We can also implement this method by creating dummy delegate method within a code.

SPSecurity.RunWithElevatedPrivileges(

                        delegate()

                        {

                                    //code goes here to do our work

                           

                        });

 

Where to Use –

This approach can be used in scenarios to read or update Site Collection, Site related objects using Full control in event handlers, features or web parts (i.e. code being executed under SharePoint Context.

Caution-

In this approach, we can’t use any SharePoint objects that were created outside the method or else the impersonation won’t work.

We also can’t use anything like SPControl.GetContextWeb(Context) because that also blows the impersonation out of the water.

Instead, we can tweak it like SPSite site = new SPSite(SPControl.GetContextSite(Context).ID). In this case, we are instantiating a new SPSite object and only using the GUID of the current site. i.e. recreation of the SPSite object with new permissions.

Also, we should dispose of the SPSite object created within the RunWithElevatedPrivileges() before exiting the scope, because that SPSite will still have the SHAREPOINT\system identity even outside of the RunWithElevatedPrivileges() scope.

RunWithElevatedPrivileges() has no effect when running in a standalone exe. 

JavaScript for Check for Published Mode of current aspx page

<div id=”contentarea”>
<!– Start implementation for Published Mode –>
<script type=”text/javascript” >
CheckForPublishing();
function CheckForPublishing()
{
var x=document.getElementById(“Ribbon.PublishTab-title”);
if(x==null)
LoadScript();

}

function LoadScript() {
var ss = document.createElement(‘script’);
var scr = ‘alert(“Well Done Amjad!!…Its working…”);’;
ss.text = scr;
ss.setAttribute(“type”, “text/javascript”);
//ss.setAttribute(“src”, “http://Google.com“);
var hh = document.getElementsByTagName(‘head’)[0];
hh.appendChild(ss);
}

</script>

<!– End implementation for Published Mode  –>
</div>

Power Shell for Adding User to SPGroup

param(
[string] $envType = $(throw “envType(PersonalDev, SharedDev, Test, Sandbox or Production)required”),
[string] $workFolder = (Get-Item (“.”)).FullName,
[string] $wspName = “MyTest.My.Intra.wsp”
)

if(-not(Get-PSSnapin | Where { $_.Name -eq “Microsoft.SharePoint.PowerShell”})) {
Add-PSSnapin Microsoft.SharePoint.PowerShell
}

$solName = “MyTest.My.Intra.wsp”

#
# Functions
#

function LogProgress($message)
{
$now = Get-Date –f “yyyy-MM-dd HH:mm:ss”
if ($isInterActiveSession -eq “True”)
{
Write-Host `n $now.ToString() -: $message
}
else
{
Write-Output ($now.ToString() + “: ” + $message) | Out-File $logFile -append
}

}

function SetPSSiteCollectionAdminArray($alAddUsersToSP)
{
[string] $UserNameID=”AddUserName”;
[string] $UserGroupID=”SPUserGroup”;
[string] $UserName;
[string] $UserGroup;
[string] $TypeOfUserID = “IsSiteCollectionAdmin”;
[string] $TypeOfUser;

$Counter=$alAddUsersToSP.Count;
for ($i = 0; $i -lt $Counter; $i++)
{
[HashTable] $ht=$alAddUsersToSP[$i];
$KeyCounter= $ht.Count;
$ht.GetEnumerator() | ForEach-Object {
[String] $Key=$_.Key;
[String] $Val=$_.Value;
if($UserNameID -eq $Key)
{
$UserName=$Val;
}
if($UserGroupID -eq $Key)
{
$UserGroup=$Val;
}
if($TypeOfUserID -eq $Key)
{
$TypeOfUser=$Val;
}

}
if($TypeOfUser -eq “Yes”)
{
$SiteCollectionAdminArray.Add($UserName);
}

}
}

[HashTable] $htSPUserGroup=@{
1 = “Home Owners”;
2 =”Home Members”;
3 =”Home Visitors”;
}

###### Start : AddUser and AddAdminUser ########

function AddUsers($alAddUsersToSP)
{
[string] $UserNameID=”AddUserName”;
[string] $UserGroupID=”SPUserGroup”;
[string] $UserName;
[string] $UserGroup;
[string] $TypeOfUserID = “IsSiteCollectionAdmin”;
[string] $TypeOfUser;

$Counter=$alAddUsersToSP.Count;
for ($i = 0; $i -lt $Counter; $i++)
{
[HashTable] $ht=$alAddUsersToSP[$i];
$KeyCounter= $ht.Count;
$ht.GetEnumerator() | ForEach-Object {
[String] $Key=$_.Key;
[String] $Val=$_.Value;
if($UserNameID -eq $Key)
{
$UserName=$Val;
}
if($UserGroupID -eq $Key)
{
$UserGroup=$Val;
}
if($TypeOfUserID -eq $Key)
{
$TypeOfUser=$Val;
}

#Write-Host “$Key : $Val”
}
if($TypeOfUser -eq “Yes”)
{
#Write-Host “I am Admin => $UserName : $UserGroup added to $siteUrl”
New-SPUser -UserAlias $UserName -Web $siteUrl -SiteCollectionAdmin
}
else
{
#Write-Host “I am not Admin => $UserName : $UserGroup added to $siteUrl”
New-SPUser -UserAlias $UserName -Web $siteUrl -Group $UserGroup
}
#Write-Host “__________________New user Added_______________________”
}
}

switch ($envType)
{
“PersonalDev”
{
$comp = Get-WmiObject -Class Win32_ComputerSystem
$hostHeader = “intra.Mydev.local”
$port = 80
$siteUrl = “http://&#8221; + $hostHeader
$appPoolName = “SharePoint – ” + $hostHeader + $port
#$solPath = (Get-ChildItem (“..\bin\Debug\” + $wspName)).FullName

}
“SharedDev”
{
$comp = Get-WmiObject -Class Win32_ComputerSystem
$hostHeader = “intra.Mydev.MyTest.com”
$port = 80
$siteUrl = “http://&#8221; + $hostHeader
$appPoolName = “SharePoint – ” + $hostHeader + $port
$solPath = $workFolder + “\” + $wspName
}
“Test”
{
$comp = Get-WmiObject -Class Win32_ComputerSystem
$hostHeader = “test-avenue.My.com”
$port = 80
$siteUrl = “http://&#8221; + $hostHeader
$appPoolName = “SharePoint – ” + $hostHeader + $port
$solPath = $workFolder + “\” + $wspName
}
“Sandbox”
{
$comp = Get-WmiObject -Class Win32_ComputerSystem
$hostHeader = “playground-avenue.My.com”
$port = 80
$siteUrl = “http://&#8221; + $hostHeader
$appPoolName = “SharePoint – ” + $hostHeader + $port
$solPath = $workFolder + “\” + $wspName
}
“Production”
{
$comp = Get-WmiObject -Class Win32_ComputerSystem
$hostHeader = “avenue.My.com”
$port = 80
$siteUrl = “http://&#8221; + $hostHeader
$appPoolName = “SharePoint – ” + $hostHeader + $port
$solPath = $workFolder + “\” + $wspName
}
default
{
throw “Error: unknown value given for parameter 1 envType”
}
}

###### Start : Hashtable : AddUser and AddAdminUser ########
[HashTable] $htMyAddUser1=@{
“AddUserName”= @($comp.Name + “\MyVisitor1”);
“SPUserGroup” = “Home Visitors”;
“IsSiteCollectionAdmin” = “No”;
}

[HashTable] $htMyAddUser2=@{
“AddUserName”= @($comp.Name + “\MyVisitor2”);
“SPUserGroup” = “Home Visitors”;
“IsSiteCollectionAdmin” = “No”;
}
[HashTable] $htMyAddUser3=@{
“AddUserName”= @($comp.Name + “\MyVisitor3”);
“SPUserGroup” = “Home Visitors”;
“IsSiteCollectionAdmin” = “No”;
}
[HashTable] $htMyAddUser4=@{
“AddUserName”= @($comp.Name + “\MyVisitor4”);
“SPUserGroup” = “Home Visitors”;
“IsSiteCollectionAdmin” = “No”;
}
[HashTable] $htMyAddUser5=@{
“AddUserName”= @($comp.Name + “\MyVisitor5”);
“SPUserGroup” = “Home Visitors”;
“IsSiteCollectionAdmin” = “No”;
}
[HashTable] $htMyAddUser6=@{
“AddUserName”= @($comp.Name + “\MyVisitor6”);
“SPUserGroup” = “Home Visitors”;
“IsSiteCollectionAdmin” = “No”;
}
[HashTable] $htMyAddUser7=@{
“AddUserName”= @($comp.Name + “\MyVisitor7”);
“SPUserGroup” = “Home Visitors”;
“IsSiteCollectionAdmin” = “No”;
}
[HashTable] $htMyAddUser8=@{
“AddUserName”= @($comp.Name + “\MyVisitor8”);
“SPUserGroup” = “Home Visitors”;
“IsSiteCollectionAdmin” = “No”;
}
[HashTable] $htMyAddUser9=@{
“AddUserName”= @($comp.Name + “\MyVisitor9”);
“SPUserGroup” = “Home Visitors”;
“IsSiteCollectionAdmin” = “No”;
}
[HashTable] $htMyAddUser10=@{
“AddUserName”= @($comp.Name + “\MyVisitor10”);
“SPUserGroup” = “Home Visitors”;
“IsSiteCollectionAdmin” = “No”;
}
[HashTable] $htMyAddUser11=@{
“AddUserName”= @($comp.Name + “\MyVisitor11”);
“SPUserGroup” = “Home Visitors”;
“IsSiteCollectionAdmin” = “No”;
}
[HashTable] $htMyAddUser12=@{
“AddUserName”= @($comp.Name + “\MyVisitor12”);
“SPUserGroup” = “Home Visitors”;
“IsSiteCollectionAdmin” = “No”;
}
[HashTable] $htMyAddUser13=@{
“AddUserName”= @($comp.Name + “\MyVisitor13”);
“SPUserGroup” = “Home Visitors”;
“IsSiteCollectionAdmin” = “No”;
}
[HashTable] $htMyAddUser14=@{
“AddUserName”= @($comp.Name + “\MyVisitor14”);
“SPUserGroup” = “Home Visitors”;
“IsSiteCollectionAdmin” = “No”;
}
[HashTable] $htMyAddUser15=@{
“AddUserName”= @($comp.Name + “\MyVisitor15”);
“SPUserGroup” = “Home Visitors”;
“IsSiteCollectionAdmin” = “No”;
}
[HashTable] $htMyAddUser16=@{
“AddUserName”= @($comp.Name + “\MyVisitor16”);
“SPUserGroup” = “Home Visitors”;
“IsSiteCollectionAdmin” = “No”;
}
[HashTable] $htMyAddUser17=@{
“AddUserName”= @($comp.Name + “\MyVisitor17”);
“SPUserGroup” = “Home Visitors”;
“IsSiteCollectionAdmin” = “No”;
}
[HashTable] $htMyAddUser18=@{
“AddUserName”= @($comp.Name + “\MyVisitor18”);
“SPUserGroup” = “Home Visitors”;
“IsSiteCollectionAdmin” = “No”;
}
[HashTable] $htMyAddUser19=@{
“AddUserName”= @($comp.Name + “\MyVisitor19”);
“SPUserGroup” = “Home Visitors”;
“IsSiteCollectionAdmin” = “No”;
}
[HashTable] $htMyAddUser20=@{
“AddUserName”= @($comp.Name + “\MyVisitor20”);
“SPUserGroup” = “Home Visitors”;
“IsSiteCollectionAdmin” = “No”;
}

##### Home Contributors
[HashTable] $htMyAddUser21=@{
“AddUserName”= $comp.Name + “\MyContributor1”;
“SPUserGroup” = “Home Members”;
“IsSiteCollectionAdmin” = “No”;
}
[HashTable] $htMyAddUser22=@{
“AddUserName”= $comp.Name + “\MyContributor2”;
“SPUserGroup” = “Home Members”;
“IsSiteCollectionAdmin” = “No”;
}
[HashTable] $htMyAddUser23=@{
“AddUserName”= $comp.Name + “\MyContributor3”;
“SPUserGroup” = “Home Members”;
“IsSiteCollectionAdmin” = “No”;
}

##### Home Owners

[HashTable] $htMyAddUser24=@{
“AddUserName”= $comp.Name + “\MyAdmin1”;
“SPUserGroup” = “Home Owners”;
“IsSiteCollectionAdmin” = “No”;
}
[HashTable] $htMyAddUser25=@{
“AddUserName”= $comp.Name + “\MyAdmin2”;
“SPUserGroup” = “Home Owners”;
“IsSiteCollectionAdmin” = “No”;
}

### Start : Add UserHash to Collection ArrayList ###
$alAddUsers = New-Object System.Collections.ArrayList ;
$alAddUsers.Add($htMyAddUser1);
$alAddUsers.Add($htMyAddUser2);
$alAddUsers.Add($htMyAddUser3);
$alAddUsers.Add($htMyAddUser4);
$alAddUsers.Add($htMyAddUser5);
$alAddUsers.Add($htMyAddUser6);
$alAddUsers.Add($htMyAddUser7);
$alAddUsers.Add($htMyAddUser8);
$alAddUsers.Add($htMyAddUser9);
$alAddUsers.Add($htMyAddUser10);
$alAddUsers.Add($htMyAddUser11);
$alAddUsers.Add($htMyAddUser12);
$alAddUsers.Add($htMyAddUser13);
$alAddUsers.Add($htMyAddUser14);
$alAddUsers.Add($htMyAddUser15);
$alAddUsers.Add($htMyAddUser16);
$alAddUsers.Add($htMyAddUser17);
$alAddUsers.Add($htMyAddUser18);
$alAddUsers.Add($htMyAddUser19);
$alAddUsers.Add($htMyAddUser20);
$alAddUsers.Add($htMyAddUser21);
$alAddUsers.Add($htMyAddUser22);
$alAddUsers.Add($htMyAddUser23);
$alAddUsers.Add($htMyAddUser24);
$alAddUsers.Add($htMyAddUser25);
### End : Add UserHash to Collection ArrayList ###

LogProgress “Adding site users”
AddUsers $alAddUsers;

Power Shell for Add on Local User

param(
[string] $envType = $(throw “envType(PersonalDev, SharedDev, Test, Sandbox or Production)required”),
[string] $workFolder = (Get-Item (“.”)).FullName,
[string] $wspName = “MyTest.My.Intra.wsp”
)

if(-not(Get-PSSnapin | Where { $_.Name -eq “Microsoft.SharePoint.PowerShell”})) {
Add-PSSnapin Microsoft.SharePoint.PowerShell
}

$solName = “MyTest.My.Intra.wsp”

function create-account ([string]$accountName = “testuser”) {
$hostname = hostname
$comp = [adsi] “WinNT://$hostname”
$user = $comp.Create(“User”, $accountName)
$user.SetPassword(“Test1234!”)
$user.SetInfo()
}

switch ($envType)
{
“PersonalDev”
{
$comp = Get-WmiObject -Class Win32_ComputerSystem
$hostHeader = “intra.Mydev.local”
$port = 80
$siteUrl = “http://&#8221; + $hostHeader
$appPoolName = “SharePoint – ” + $hostHeader + $port
#$solPath = (Get-ChildItem (“..\bin\Debug\” + $wspName)).FullName

}
“SharedDev”
{
$comp = Get-WmiObject -Class Win32_ComputerSystem
$hostHeader = “intra.Mydev.MyTest.com”
$port = 80
$siteUrl = “http://&#8221; + $hostHeader
$appPoolName = “SharePoint – ” + $hostHeader + $port
$solPath = $workFolder + “\” + $wspName
}
“Test”
{
$comp = Get-WmiObject -Class Win32_ComputerSystem
$hostHeader = “test-avenue.My.com”
$port = 80
$siteUrl = “http://&#8221; + $hostHeader
$appPoolName = “SharePoint – ” + $hostHeader + $port
$solPath = $workFolder + “\” + $wspName
}
“Sandbox”
{
$comp = Get-WmiObject -Class Win32_ComputerSystem
$hostHeader = “playground-avenue.My.com”
$port = 80
$siteUrl = “http://&#8221; + $hostHeader
$appPoolName = “SharePoint – ” + $hostHeader + $port
$solPath = $workFolder + “\” + $wspName
}
“Production”
{
$comp = Get-WmiObject -Class Win32_ComputerSystem
$hostHeader = “avenue.My.com”
$port = 80
$siteUrl = “http://&#8221; + $hostHeader
$appPoolName = “SharePoint – ” + $hostHeader + $port
$solPath = $workFolder + “\” + $wspName
}
default
{
throw “Error: unknown value given for parameter 1 envType”
}
}

[string] $UserName=””
[string] $UserNameMy=”MyVisitor”
$Counter=21
Write-Host “Creating MyVisitor Users:”
for ($i = 1; $i -lt $Counter; $i++)
{
$UserName= $UserNameMy + $i
Write-Host “$UserName”
create-account $UserName
}

$UserNameMy=”MyContributor”
$Counter=4
Write-Host “Creating MyContributor Users:”
for ($i = 1; $i -lt $Counter; $i++)
{
$UserName= $UserNameMy + $i
Write-Host “$UserName”
create-account $UserName
}

$UserNameMy=”MyAdmin”
$Counter=3
Write-Host “Creating MyAdmin Users:”
for ($i = 1; $i -lt $Counter; $i++)
{
$UserName= $UserNameMy + $i
Write-Host “$UserName”
create-account $UserName
}

Write-Host “Done!”

Import and Export term sets manage metadata to CSV – PS script

#Add-PSSnapin Microsoft.SharePoint.PowerShell 
#[Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Taxonomy") 

param
( 
[string] $outPutDir = (Get-Item (".")).FullName,
[string] $siteURL = "http://MyTest:55555", 
[string] $mmsServiceName = "Managed Metadata Service", 
[string] $grpName = "[GroupNameOfTermSet]",
[string] $termSetName = $(throw "termSetName is required"),
[string] $fileName = $(throw "fileName is required")
)

try        
{ 
write-host "Here"           
	$taxonomySite = Get-SPSite $siteURL             
	$taxSession = Get-SPTaxonomySession -site $taxonomySite 
		try            
		{                 
			$termStore = $taxSession.TermStores[$mmsServiceName]; 
			if ($termStore -ne $null)                 
			{                     
				try                    
				{                         
					$termGroup = $termStore.Groups[$grpName]; 
					if ($termGroup -ne $null)                         
					{                             
						try                            
						{ 
							$termSet = $termGroup.TermSets[$termSetName];                                    
							if ($termSet -ne $null)                                 
							{                                     
								[string]$csvDir = "";
								$csvDir = $outPutDir;                                     
								$outPutFile = $csvDir + "\" + "$fileName";                                        
								$sw = New-Object System.IO.StreamWriter($outPutFile);    
								$sw.writeline('"Term Set Name","Term Set Description","LCID","Available","Term Description","Level 1 Term","Level 2 Term","Level 3 Term","Level 4 Term","Level 5 Term","Level 6 Term","Level 7 Term"');                                     
								[Byte[]] $ampersand = 0xEF,0xBC,0x86;                                     
								#$loop = $termGroup.TermSets.Count;                                     
								#$count = 1; 
								if($TermSet.TermsCount -ne 0)                                             
								{                                                 
									$topTermOutput = '"' + $TermSet.Name.Replace([System.Text.Encoding]::UTF8.GetString($ampersand), "&") + '","' +  $TermSet.Description + '","' + $TermSet.Languages + '","' +  $TermSet.IsAvailableForTagging + '","';                                                    
									foreach($childTerm in $TermSet.Terms)                                             
									{                                                 
										if($childTerm.TermsCount -ne 0)                                                 
										{                                                     
											#$topTermOutput = '"' + '","' +  $TermSet.Description + '","' + $TermSet.Languages + '","' +  $TermSet.IsAvailableForTagging + '","';                                                      
											$heritage = $topTermOutput + '","' + $childTerm.Description + '","' + $childTerm.Name.Replace([System.Text.Encoding]::UTF8.GetString($ampersand), "&") + '"';                                                    
											foreach($secondLevelTerm in $childTerm.Terms)                                                     
											{
												if($secondLevelTerm.TermsCount -ne 0)                                                         
												{                                                             
													foreach($thirdLevelTerm in $secondLevelTerm.Terms)                                                             
													{
														if($thirdLevelTerm.TermsCount -ne 0)                                                                 
														{                                                                     
															foreach($fourthLevelTerm in $thirdLevelTerm.Terms)                                                                     
															{                                                                         
																if($fourthLevelTerm.TermsCount -ne 0)                                                                         
																{                                                                             
																	foreach($fifthLevelTerm in $fourthLEvelTerm.Terms)                                                                             
																	{                                                                                 
																		if($fifthLevelTerm.TermsCount -ne 0)                                                                                 
																		{                                                                                     
																			foreach($sixthLevelTerm in $fifthLevelTerm.Terms)                                                                                     
																			{   
																				if($sixthLevelTerm.TermsCount -ne 0)                                                                                         
																				{                                                                                             
																					foreach($seventhLevelTerm in $sixthLevelTerm.Terms)                                                                                             
																					{                                                                                                 
																						$heritage = $topTermOutput + '","' + $childTerm.Name.Replace([System.Text.Encoding]::UTF8.GetString($ampersand), "&") + '","' + $secondLevelTerm.Name.Replace([System.Text.Encoding]::UTF8.GetString($ampersand), "&") + '","' + $thirdLevelTerm.Name.Replace([System.Text.Encoding]::UTF8.GetString($ampersand), "&") + '","' + $fourthLevelTerm.Name.Replace([System.Text.Encoding]::UTF8.GetString($ampersand), "&") + '","' + $fifthLevelTerm.Name.Replace([System.Text.Encoding]::UTF8.GetString($ampersand), "&") + '","' + $sixthLevelTerm.Name.Replace([System.Text.Encoding]::UTF8.GetString($ampersand), "&") + '","' + $seventhLevelTerm.Name.Replace([System.Text.Encoding]::UTF8.GetString($ampersand), "&") + '"';                                                                                                 
																						$sw.writeline($heritage);                                                                                                                                                                                            
																					}                                                                                         
																				}                                                                                         
																				else                                                                                        
																				{                                                                                             
																					$heritage = $topTermOutput + '","' + $childTerm.Name.Replace([System.Text.Encoding]::UTF8.GetString($ampersand), "&") + '","' + $secondLevelTerm.Name.Replace([System.Text.Encoding]::UTF8.GetString($ampersand), "&") + '","' + $thirdLevelTerm.Name.Replace([System.Text.Encoding]::UTF8.GetString($ampersand), "&") + '","' + $fourthLevelTerm.Name.Replace([System.Text.Encoding]::UTF8.GetString($ampersand), "&") + '","' + $fifthLevelTerm.Name.Replace([System.Text.Encoding]::UTF8.GetString($ampersand), "&") + '","' + $sixthLevelTerm.Name.Replace([System.Text.Encoding]::UTF8.GetString($ampersand), "&") + '"';                                                                                             
																					$sw.writeline($heritage);                                                                                         
																				}                                                                                     
																			}                                                                                 
																		}                                                                                 
																		else                                                                                
																		{                                                                                     
																			$heritage = $topTermOutput + '","' + $childTerm.Name.Replace([System.Text.Encoding]::UTF8.GetString($ampersand), "&") + '","' + $secondLevelTerm.Name.Replace([System.Text.Encoding]::UTF8.GetString($ampersand), "&") + '","' + $thirdLevelTerm.Name.Replace([System.Text.Encoding]::UTF8.GetString($ampersand), "&") + '","' + $fourthLevelTerm.Name.Replace([System.Text.Encoding]::UTF8.GetString($ampersand), "&") + '","' + $fifthLevelTerm.Name.Replace([System.Text.Encoding]::UTF8.GetString($ampersand), "&") + '"';                                                                                     
																			$sw.writeline($heritage);                                                                                 
																		} 
																	}                                                                         
																}                                                                         
																else                                                                        
																{                                                                             
																	$heritage = $topTermOutput + '","' + $childTerm.Name.Replace([System.Text.Encoding]::UTF8.GetString($ampersand), "&") + '","' + $secondLevelTerm.Name.Replace([System.Text.Encoding]::UTF8.GetString($ampersand), "&") + '","' + $thirdLevelTerm.Name.Replace([System.Text.Encoding]::UTF8.GetString($ampersand), "&") + '","' + $fourthLevelTerm.Name.Replace([System.Text.Encoding]::UTF8.GetString($ampersand), "&") + '"';                                                                             
																	$sw.writeline($heritage);                                                                         
																}                                                                     
															}                                                                 
														} 
														else                                                                
														{                                                                     
															$heritage = $topTermOutput + '","' + $childTerm.Name.Replace([System.Text.Encoding]::UTF8.GetString($ampersand), "&") + '","' + $secondLevelTerm.Name.Replace([System.Text.Encoding]::UTF8.GetString($ampersand), "&") + '","' + $thirdLevelTerm.Name.Replace([System.Text.Encoding]::UTF8.GetString($ampersand), "&") + '"';                                                                     
															$sw.writeline($heritage);                                                                 
														}                                                             
													}                                                         
												} 
												else                                                        
												{                                                             
													$heritage = $topTermOutput + '","' + $childTerm.Name.Replace([System.Text.Encoding]::UTF8.GetString($ampersand), "&") + '","' + $secondLevelTerm.Name.Replace([System.Text.Encoding]::UTF8.GetString($ampersand), "&") + '"';                                                             
													$sw.writeline($heritage);                                                         
												}                                                     
											}                                                 
										}
										else                                                
										{                                                      
											$heritage = $topTermOutput + '","' + $childTerm.Name.Replace([System.Text.Encoding]::UTF8.GetString($ampersand), "&") + '"';                                                      
											$sw.writeline($heritage);                                                 
										}                                             
									}                                         
								}  
								else                                        
								{                                              
									$heritage = $topTermOutput + '","' + $childTerm.Name.Replace([System.Text.Encoding]::UTF8.GetString($ampersand), "&") + '",,,,,,,' ;                                                                                              
									$sw.writeline($heritage);                                         
								}                                     
							}                                 
						} 
						catch                                
						{                                     
							return "Problem occurred while creating the export file."                                
						}                                 
						$sw.close();                                 
						write-host "Your CSV has been created at $outPutFile";                                 
					} 
					else                            
					{                                 
						return "Termset $termSet does not exist in the term store group $term";                             
					}                         
				}                         
				catch [System.Exception]                         
				{                             
					write-host($_.Exception)                             
					"Unable to acquire the termset $termSetName from the term group $grpName"                        
				}                     
			}
			else                    
			{                         
				return "Term store group $grpName does not exist in the term store $mmsServiceName";                     
			}                 
		}                 
		catch                
		{                     
			"Unable to acquire term store group $grpName from $mmsServiceName"                
		}             
	}  
	catch            
	{                 
		"Unable to acquire session for the site $siteURL";             
	}         
finally        
{             
	$ErrorActionPreference = "Continue";         
}

Reference Link : http://sharepoint-talk.blogspot.com/2011/08/exporting-and-importing-term-set-to-csv.html