allBlogsList

Custom Sitecore Powershell Command

January 03rd, 2016

Create a class called BatchImportCommandlet inheriting from the PSCmdlet.

using Microsoft.Practices.ServiceLocation;
using Nerium.Business.Insite.ImportExport;
using System.Management.Automation;

namespace Nerium.SitecoreExtensions.SitecorePowerShellExtensions
{
public class BatchImportCommandlet : PSCmdlet
{
}
}

The goal is to call the commandlet with the following name.

import-batch

To specify the command name we will use the Cmdlet property in the class declaration.

[Cmdlet(“Import”, “Batch”)]
public class BatchImportCommandlet : PSCmdlet
{
}

One of the flexibilties of commandlet’s is supporting the ability to pass properties. The property will be required and will be specified in the code using the Manadartory Property. To verify that the value passed is not a empty string I add the ValidateNotNullOrEmpty property. This will allow Powerscript to validate the property is correctly set before executing the code.

[Cmdlet(“Import”, “Batch”)]
public class BatchImportCommandlet : PSCmdlet
{
[Parameter(Mandatory = true)]
[ValidateNotNullOrEmpty]
public string FileName { get; set; }
}

The next step to creating a Powershell Commandlet is by implementing the logic that will be executed. This is implemented by the ProcessRecord function.

protected override void ProcessRecord()
{
bool result = ERPImport.Import(FileName);
}

After the code has been run we want to return the results to the user. To return the results we use the WriteObject.

protected override void ProcessRecord()
{
bool result = ERPImport.Import(FileName);

if(utility.Import(FileName))
WriteObject(“Success”);
else
WriteObject(“Failure”);
}

The full class for BatchImportCommandlet is below.

using Microsoft.Practices.ServiceLocation;
using Nerium.Business.Insite.ImportExport;
using System.Management.Automation;

namespace Nerium.SitecoreExtensions.SitecorePowerShellExtensions
{
[Cmdlet(“Import”, “Batch”)]
public class BatchImportCommandlet : PSCmdlet
{
[Parameter(Mandatory = true)]
[ValidateNotNullOrEmpty]
public string FileName { get; set; }

protected override void ProcessRecord()
{
bool result = ERPImport.Import(FileName);

if(utility.Import(FileName))
WriteObject(“Success”);
else
WriteObject(“Failure”);
}
}
}

Finally compile the code and place the dll in the Sitecore bin folder. Then run the command in the Sitecore Powershell Console

Import-Batch -FileName “Foo.xml”

The above approach will allow you to extend Sitecore Powershell to call customer .Net code.