This is not likely to be something you use on a day to day basis, and I can see how some people might disagree with this method – preferring to use other techniques e.g. SharePoint project types etc in VS.
I just see this as another way to skin the same cat! A very handy tool to have in your box.
I have used this for different things, but provisioning lists and adding some content to those lists a common thing. It’s much easier to use PowerShell to do certain things, deploying a solution every time is just a pain and not overly good use of time waiting for VS to do its thing and recycle app pools left right and centre – so I work with PowerShell on my dev box.
This then comes in when deploying to stage or production (yes, at this point you could create the artefacts perfectly in your VS solution, but time is money people…spending hours working and essentially still be at the same point I am now, just doesn’t interest me in the slightest – I have no interest in writing code just for the sake of writing code, it much achieve something).
However, if my project/solution were to be sold for mass reuse on farms that were totally out of my control – I would notuse this method.
You need to add a reference to System.Management.Automation
I created a simple class called PowerShellProxy that has a couple of helper methods, but this being the important one!
public static void RunFromFile(string filePath, bool addSharePointSnapIn) { #region Arg Validation if (String.IsNullOrEmpty(filePath)) { throw new ArgumentNullException("filePath", "Cannot be null or empty"); } if (!File.Exists(filePath)) { throw new FileNotFoundException("File not found", filePath); } #endregion try { PowerShell ps = PowerShell.Create(); if (addSharePointSnapIn) { ps.AddScript("Add-PsSnapin Microsoft.SharePoint.PowerShell -ErrorAction Continue"); } string script = ReadFileContent(filePath); ps.AddScript(script); var result = ps.Invoke();
You can then just pass in the file path of your ps1 file and you’re away. Personally I have created a folder within the Layouts folder in my VS solution – that way it’s nice and neat and easy for source control.
More:
Image may be NSFW.Clik here to view.
