PowerShell Script to Add Account to “Allow Logon Locally” privilege on Local Security Policy


As you know the SharePoint Farm Account must have privileges to logon locally for getting “User Profile Service Application” to work.

Today I created a PowerShell script that adds the given account to the “Allog Logon Locally” privilege in the Local Security Policy.

1. My account is “DOMAIN\sp_farm”

2. I start “secpol.msc” (“Local Security Policy”) on the local farm server

image

3. I’m looking for “Allow Logon Locally”. The account “sp_farm” is not in this setting.

image

4. I execute the script to add the account.

image

5. Then I reload the “Local Security Policy” or close and reopen the MMC.

image

6. Now the account in in the setting:

image

You can download the script here:

http://gallery.technet.microsoft.com/PowerShell-script-to-add-b005e0f6

This is the script:

image

BTW: A little trick for development in Visual Studio 2010 – Start PowerShell scripts that need to run in an x64 context by double click from Solution Explorer


For development and some related tasks I use PowerShell, of course. – I store the PowerShell scripts in my projects as part of them. They are part of the source code and they are saved in the source control.

If I need to run such a script I start it directly from Solution Explorer in VS2010.

Therefore I’ve set the default “open with…” to “powershell.exe”

image

image

image

If you have done this you can run every “.ps1” script file by double click in Solution Explorer!!

BUT… VS2010 itself is 32bit! – If you start an architecture independend process like “poweshell.exe” from within VS2010 it runs in 32bit environment! But sometimes you need to run a 64 version of PowerShell, e.g. for some SharePoint tasks that need an 64 bit environment.

Therefore I’ve created a little App “StartPS64”:

1. In VS2010 create a new Project of type “Console Application”

2. Open the project’s properties, select the “Build” tab and change “Platform target” to x64.

SNAGHTML57d9e4d

3. Edit “program.cs” and insert this code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace StartPS64
{
    class Program
    {
        static void Main(string[] args)
        {
            string fullname = System.IO.Path.GetFullPath(args[0]);
            if( !System.IO.File.Exists(fullname) )
            {
                Console.WriteLine("Script does not exist!");
                Console.ReadKey();
                return;
            }

            Process.Start(@"c:\windows\system32\windowspowershell\v1.0\powershell.exe", fullname);
        }
    }
}

4. Compile it.

5. Specify the build “startps64.exe” as new “default application” for “.ps1” files in VS2010 as described above.

6. Now every “.ps1” file started from the Solution Explorer will run in an 64 bit environment and can execute SharePoint cmdlets!

PowerShell Tool to Enumerate the Content Type Usage in SharePoint 2010


A customer of mine has the problem that he wants to remove a Web Content Type but SharePoint says the content type is still in use.

Therefore I created a tool for enumerating all web and list content types of all sites.

The following script scans the SharePoint farm and creates a Windows form with a Treeview like this:

image

(Web) = Web Content Types

(List) = List Content Types

The tool show the content type inheritence:

image

Here you see the List Content Type “Image” that based on the Web Content Type “Image” that based on the Web Content Type “Rich Media Asset” that based on Web Content Type “Document” that is inherited from the “System” Content Type.

It’s possible to open the content type management site by clicking “_open management site” or open the related list or web by clicking “_open list” or “_open web”.

This is the script:

#region Init
    Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
    [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint") | Out-Null
    [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")  | Out-Null
    cls
#endregion

#region Form
    $form = New-Object System.Windows.Forms.Form

    $button = New-Object System.Windows.Forms.Button
    $treeview = New-Object System.Windows.Forms.TreeView

    $form.SuspendLayout()

    $button.DialogResult = [System.Windows.Forms.DialogResult]::Cancel
    $button.Dock = [System.Windows.Forms.DockStyle]::Bottom
    $button.Location = (new-object System.Drawing.Point(0, 250))
    $button.Name = "button1"
    $button.Size = (new-object System.Drawing.Size(292, 23))
    $button.TabIndex = 0
    $button.Text = "Close"
    $button.UseVisualStyleBackColor = $true

    $treeview.Dock = [System.Windows.Forms.DockStyle]::Fill
    $treeview.Location = (new-object System.Drawing.Point(0, 0))
    $treeview.Name = "treeView1"
    $treeview.Size = (new-object System.Drawing.Size(292, 250))
    $treeview.TabIndex = 1

    $form.AutoScaleDimensions = new-object System.Drawing.SizeF(6.0, 13.0)
    $form.AutoScaleMode = [System.Windows.Forms.AutoScaleMode]::Font
    $form.ClientSize = (new-object System.Drawing.Size(292, 273))
    $form.Controls.Add($button)
    $form.Controls.Add($treeview)
    $form.Name = "Content Type Usage "
    $form.Text = "Content Type Usage / https://ikarstein.wordpress.com"
    $form.ResumeLayout($false)
#endregion

$list = @{}

$treeview.add_NodeMouseDoubleClick({
    param($sender, $eventArgs)
    if($eventArgs.Node.Tag -ne $null ) {
        [System.Diagnostics.Process]::Start($eventArgs.Node.Tag)
    }
});

function analyseWeb {
    param([Microsoft.SharePoint.SPWeb]$web) 
    
    $web.ContentTypes | % {
        $ct = $_
        $global:list += @{"$($ct.Id)"=$ct}
    }
    
    $web.lists | % {
        $_.ContentTypes | % {
            $ct = $_
            $global:list += @{"$($ct.Id)"=$ct}
        }
    }
    
    $web.Webs | % {
        analyseWeb -web $_
    }
}

function reorder {
    param([Microsoft.SharePoint.SPContentType]$p = $null, [int]$intend, [System.Windows.Forms.TreeNode]$parentNode)
    
    if( $p -eq $null ) {
        $ct = $list["0x"]

        $tn = New-Object System.Windows.Forms.TreeNode("System")
        $tn.ToolTipText = "0x"
        $parentNode.Nodes.Add($tn) | Out-Null
        
        reorder -p $ct -intend 0 -parentNode $tn
    } else {
        ($list.Values | ? {$_.Id.IsChildOf($p.Id) -and $_ -ne $p} | sort @{Expression={$_.Id.ToString().Length}}, $_.Id.ToString() ) | % {
            $ct = $_
            $type=""
            $url=""
            $tn = $null

            if( $ct.ParentList -ne $null ) {
                $type="(List) $($ct.Name) / List: $($ct.ParentList.Title) / Id: $($ct.Id.ToString())"            
                $url = $ct.parentweb.url + "/_layouts/ManageContentType.aspx?ctype=" + $ct.Id.ToString()+"&List="+$ct.ParentList.Id.ToString()
                
                #http://<domain>/sites/<web>/_layouts/ManageContentType.aspx?List=%7B111963EB%2DF504%2D49EC%2DA21B%2D814319718684%7D&ctype=0x010100644EE9F5F657474B92A2716207BB5DE2
                
                $tn = New-Object System.Windows.Forms.TreeNode($type)
                $tn1 = New-Object System.Windows.Forms.TreeNode("_open management site")
                $tn1.Tag = $url
                $tn.Nodes.Add($tn1) | Out-Null
                
                $tn2 = New-Object System.Windows.Forms.TreeNode("_open list")
                $tn2.Tag = $ct.ParentWeb.Site.MakeFullUrl($ct.ParentList.DefaultViewUrl)
                $tn.Nodes.Add($tn2) | Out-Null
            }else {
                $type="(Web) $($ct.Name) / Id: $($ct.Id.ToString())"
                $url = $ct.parentweb.url + "/_layouts/ManageContentType.aspx?ctype=" + $ct.Id.ToString()
            
                #http://<domain>/sites/<web>/_layouts/ManageContentType.aspx?ctype=0x0100CF8FCF53E9FA451CB145093F830B1762
                $tn = New-Object System.Windows.Forms.TreeNode($type)
                $tn1 = New-Object System.Windows.Forms.TreeNode("_open management site")
                $tn1.Tag = $url

                $tn.Nodes.Add($tn1) | Out-Null
                $tn2 = New-Object System.Windows.Forms.TreeNode("_open web")
                $tn2.Tag = $ct.ParentWeb.Url
                $tn.Nodes.Add($tn2) | Out-Null
            }

            $parentNode.Nodes.Add($tn) | Out-Null
        
            reorder -p $ct -intend ($intend+1) -parentNode $tn
        }
    }
}

if($fileName -ne $null ) { 
    Remove-Item -Path $fileName -Confirm:$false -ErrorAction SilentlyContinue
}

#you can filter the processed site collections in the following line
Get-SPSite -Limit all <#| select -first 1 -Skip 10#> | % {
    $site = $_
    $tn = New-Object System.Windows.Forms.TreeNode("Site: $($site.Url)")
    $treeview.Nodes.Add($tn)
    
    $rootWeb = $site.RootWeb
    
    analyseWeb -web $rootWeb
    
    reorder -parentNode $tn
    
    $rootWeb.Dispose()
    $site.Dispose()
}

$form.ShowDialog() | out-null

“SPWebPSConsole”: Web based PowerShell Console for SharePoint (A new project on Codeplex)


This project is a stand-alone clone of my project „Web based PowerShell Console” released on 2011-09-02 on Codeplex and in this blog article:

https://ikarstein.wordpress.com/2011/09/02/webpsconsole-web-based-powershell-console-a-new-project-on-codeplex/

I’ve adapted the project to run in the SharePoint 2010 Central Administration.

The project is on Codeplex: http://spwebpsconsole.codeplex.com

To install the project just by deploying the solution. The SharePoint feature will automatically be activated in the Central Administration Web Application without need of further actions.

In the “System Settings” section of the CA you’ll find a new link:

image

Just click it and you will get this:

image

image

The SharePoint PowerShell SnapIn is loaded automatically so that you can start immediately to execute SharePoint Cmdlets!

Here is an example:

“Get-SPSite”

image

Or this one:

image

Request for value for missing parameter “Path” of Cmdlet “Backup-SPSite”

image

Final output:

image

The project is “BETA”. I need your help to improve the project. Please feel free to test it or to extend it. But if you do so please send me your results!

Have fun!

“WebPSConsole”: Web based PowerShell Console (A new project on Codeplex)


Starting at 12th of September 2011 I’ll be freelancer. – In August I had some vacation days to spend. – So I created a new project for me – and for you.

I call it “Web based PowerShell Console” or “WebPSConsole”.

It is a full featured Browser based PowerShell console that enables you to work on a server machine remotely. It’s like PowerShell remoting but it’s not the same. While PowerShell remoting uses “WinRM” the tool that I’ve created uses a “normal” PowerShell host that will be executed in an IIS environment. (Please see my comment related to “PowerGUI Pro Mobile Shell” at the end of this article.)

That means: With my tool you will have a ASP.NET 4.0 based Web Application that can be accessed by a browser. The ASP.NET web app has a .ASPX site and some code behind. On the server in the ASP.NET context a PowerShell Host developed by me is running that accepts commands send by the clients Browser. If a command is send it will be executed by the PowerShell Host. All output is send back to the clients Browser.

It’s on Codeplex: http://webpsconsole.codeplex.com with all source code! – It’s ALPHA. I’ve done lots of testing but I’m a single developer with a single machine… I’d be happy to get your improvements or experiences!

Lets have a look at the app:

image

That is the “GUI”. The black frame will contain the output of the server side PowerShell session.

Let’s enter a command.

get-childitem c:\windows | select -first 5

image 

After clicking “Send” the command is send to the server. The server executes the command and returns the PowerShell output.

Let’s try this:

get-credential

image 

You see the blue colored input box for the credential information input.

Here you see the implemented “session timeout”:

image

After 15 minutes of inactivity you’ll get a warning. After 20 minutes the session will be terminated. After termination you are not able to access the old session including session history!

Let’s try this:

a$ = read-host

image 

Here you get an input field for a single line of text. The output is stored in variable $a. Let’s check the content of variable $a after sending the input:

image 

Now let’s test the functionality of completing missing cmdlet parameters:

get-content

image 

image

Leave the last line empty and click “Send”.

image

You get:

image

Now let’s test the “choice” functionality:

image 

After “Send” you get:

image 

You see here the blue colored choice input field. If you choose “Halt Command” in this case the “Hello Ingo” command will not be executed:

image 

If you select “Cancel” in such cases the complete PowerShell pipeline will be stopped! Not only the current command!

You can set colors a you need to:

image 

Than “Send” and test it with:

image 

You’ll get:

image

Now let’s have a look at the function “Download console as RTF”. You’ll find the link above the console frame.

image 

Click “Open”.

image 

This is a Rich Text Format copy of the complete console output! – A “Clear-Host” will not clear this output! – This file can only be downloaded while the current session running. After the session ends you will not be able to access the information anymore!

Let’s try “Show current buffer”. This command is above the console frame too.

image 

Here you get the “real” PowerShell buffer as HTML. This page can be save.

Let’s try:

clear-host

image 

Open “Show current buffer” again:

image 

(It’s empty now because clear-host did clear the PowerShell buffer!)

A word to the keyboard usability:

In the command input field you can use ESCAPE to clear the input field.

You can use CTRL+ENTER to send the command.

In other input fields (choice, credential, read-line,…) except “Read-Key” (see below) you can use ESCAPE to cancel the current operation and pipeline.

You can use there ENTER to send your entered data.

You can use TAB and SHIFT+TAB to navigate inside the input frame: input field, Send button and Cancel button.

The “Trace log” is an optional frame that maybe shows more information about your server connection and the “work behind”. Just click the line and the frame will be shown:

image 

(“Send buffer as HTML” is caused by the “Show current buffer” function.)

You can close the PowerShell session by clicking the “x” in the dialog title (beside “v0.1.0.0”):

image 

Now you can close the Browser or click “Ok” to start a new session. Or reload the Browser page to create a new session.


Setup

Now I want to tell you how to install the project.

First of all you need IIS. This can be installed on Windows 7 too.

You need a user account for executing PowerShell at server side. This account is used by every user of WebPSConsole: Each user of WebPSConsole will be impersonated at the server with the “execution account”. Here you should choose the account very carefully.

1.

Create a directory on the server where you store the binaries. You create a folder “c:\inetput\webpsconsole”.

image 

 

2.

Copy the binaries there.

image 

 

3.

Open IIS Manager.

Create a new Application Pool for the “execution account”. This account need to execute ASP.NET 4.0 code.

image 

Select “Classical Mode” for the application pool! – Please check the settings. In my case the settings were not used. After creating the app pool I had to edit it and set “Pipeline Mode” and “Framework Version” again!!!

 

4.

Create a new web application “WebPSConsole” using the previously created application pool.

Right click the “Sites” node in IIS Manager.

image 

You get this dialog. Fill in your specific informations. Here is my sample. I’ll use “ikWebPSConsole” as host header name in this setup demo because the host header “webpsconsole” already exists for development purpose.

image 

Click the “Select” button beside “Application pool:

image 

“OK”.

My sample data:

image 

(In order to get this working on my machine I have to edit c:\windows\system32\driver\etc\hosts and insert “ikWebPSConsole” as new local DNS entry.)

 

5.

Change the Authentication settings. Disable “Anonymous Access” and enable “Windows Authentication”.

Select the web app in the treeview. On the right side double click “Authentication”.

image 

You get:

image 

First double click “Anonymous Authentication” and deactivate it!

image 

Now enable “Windows Authentication” the same way!

 

6.

You should restrict the usage of the web app by setting access restrictions.

image 

There you can grant or deny access to the web app for specific users, e.g. administrators.

As an example: Here only “DOMAIN\Administrator” will have access to WebPSConsole.

image 

You should enable SSL.

I’ve done this already in the setup example above while creating the web app.

You could use “SSL client certificates” to protect the web app.

7. Test the app.

Security

  • I’ts as secure as you configure it!
  • You can restrict the rights of the console on the server by selecting a carefully configured user account as application pool account. You don’t have to configure this user to be “local admin” 😉
  • You can use SSL! (As shown above)
  • You can use Client-SSL-Certificates!
  • You can restrict client IP addresses!
  • You can restrict access by secifying users (as shown above).
  • BUT be sure you know what you do – as always 😉

Limitations

  • It’s not as fast as a local PowerShell because of the client-server-interaction.
  • Currently it runs only under the user context of the application pool. There should be “real” impersonation of the logged in user. But this did not work.
  • It consumes memory on the server because of the data saved on the server in the session. Be sure to monitor the servers memory usage if you deploy it on live servers!
  • There is not “Progress” support at the moment!

 

Ideas for future features:

  • Command completion (like “Intellisence”)
  • Client side syntax check
  • “Color code”

Please help me to impove the app! – Please post comment of your experiences!


Have fun!


For this project I’ve used:

 

 

A word to PowerGUI Pro MobileShell

As I said I’ve developed this project in my last vacation. After finishing v0.1.0.0 I’ve seen PowerGUI Pro MobileShell by Quest Software
. It’s based on the same idea as my project but is older and has more features I think. I only know a YouTube video of it because I do not know the commercial version of PowerGUI. – Beside this the free PowerGUI tool is my favorite PowerShell IDE. – For use on a live server you should think about using PowerGUI Pro MobileShell!

SharePoint PowerShell Timer Jobs: Run PowerShell scripts in SharePoint Timer Service context.


I’ve created a new project that combines my two primary technical passions: SharePoint 2010 and PowerShell. Smiley

The project “SharePoint PowerShell Timer Jobs” lets you create, modify and delete SharePoint timer jobs that run PowerShell scripts in the context of the SharePoint Timer Service!

It’s on Codeplex – including source code:

I hope you will love it! (If so please let me know!) – Please feel free to extend the project. If you do so please share your extensions with the community!!!

PowerShell Timer Jobs could be very useful. I’ll use it for “SharePoint Warmup”. Therefore I create a PowerShell script some months ago. This I will port to a PowerShell Timer Job and post it on my blog…

 

Now let’s have a look…

 

Here’s a screenshot of the “System Settings” page of the SharePoint 2010 Central Administration:

pic01

Use “Manage PowerShell Jobs” to create, modify or delete PowerShell jobs.

On the admin page you can select an existing timer job or select “<new>” to create a new one.

If you create a new one you have to configure it and name it. Then save the timer job. After that you’ll be able to edit the script.

In this screenshot you see an existing timer job:

Here the “Edit” button is enabled. The script below the “Edit” button is read only!

Click “Edit”… Here is what you will see:

In the Edit dialog you can enter your PowerShell script and save it.

The Edit dialog does not validate your script! It have to be valid. Or you will see errors in the history list.

At the management page you can enable or disable existing jobs using the checkbox. Don’t forget to click the “Update” button after you changed something!

At the “System Settings” page of the Central Administration you see the link “Review PowerShell Job Execution History”. Using this link you will be redirected to the history list. All outputs of all of your PowerShell jobs will be collected here.

The list will not be cleared automatically! – But… You could create a SharePoint PowerShell Timer Job for this purpose 🙂 …

The last thing you should know: All the jobs you create are accessible at common SharePoint Job admin pages  like “Review Job definitions” and “Check job status” (Central Administration -> Monitoring)

Here you see a screenshot of the “Review Job definitions” page of SharePoint 2010:

This is a screenshot of the Job definitions detail page:

At least a screenshot of the “Check job status” page of SharePoint:

Some more details…

The PowerShell script of each timer job will be executed in a dedicated PowerShell runtime environment (“Runspace”).

For the PowerShell runspace I’ve created a PowerShell Host implementation. This implementation does not support any user interaction! Be sure your script does not need to interact with the user, e.g. for delete confirmation.

The script you enter will be surrounded with this code:

Add-PSSnapIn Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue | out-null  
$o = Invoke-Command -ScriptBlock 
{ 
<your code> 
} 
$p = $o | out-string 
$p
 

For script development you should use this code frame too! But if you copy the script code from the development tool, e.g. Windows PowerShell ISE, to PowerShell Timer Jobs, be sure only to copy <your code>.

Furthermore you need to enable the execution of unsigned PowerShell scripts in the context of the SharePoint Timer Service. This service normally runs under the Farm account. Have a look into the “Services” management console.

Before you use the tool be sure you know what you do! – PowerShell scripts can damage your farm! BE CAREFULL!!!!I’m not responsible for any damages.

You shoud test the tool in your own environment. There could be errors in the tool!!! I’ve tested it in my dev environment, but maybe in yours it does not work properly!

Feel free to extend the tool. But if you do so please publish your code to the community.

You must not remove my name or the link to the projects homepage from any file or page of the project. – Please don’t do that. Thanks 🙂

 TO USE THE PROJECT…

…you need to deploy the .WSP file to sharepoint and activate the SharePoint features in the Central Administration. The history list have to resist on the CA!!!