Category: PowerShell

No Default Subscription?

Set-AzureWebsite : No default subscription has been designated. Use Select-AzureSubscription -Default <subscriptionName> to set the default subscription.

*doh* Again I’ve used PowerShell comandlets for Azure classic instead of Resource Manager 🙁

Reminder: Always check for the magic “Rm” chars in the command, if a resource cannot be found.

HowTo use Azure cmdlets in Azure Schedule

A Runbook schedule can be triggered every hour. If you need a smaller interval, like every minute, you can use the Azure Scheduler to do so.
So I went to the Azure Portal, created an Azure Schedule instance (with a job collection tier of at least basic, to be able to create schedules that are triggered every minute) and called a Runbook via webhook.

The Runbook contains a cmdlet that results in an error 🙁
Get-AzureRmMetric : The term 'Get-AzureRmMetric' is not recognized as the name of a cmdlet, function, script file, or
operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try
again.

Azure cmdlets can be made available through the Automation Account the Runbook is using. The “Browse Gallery” link will let you find and choose the necessary cmdlets.

The error message above appears, because a) the cmdlet was not installed and b) the referenced version of AzureRM.profile was to old. Fortunately the problem can be resolved easily by upgrading the Azure modules.

After all modules are up to date, I could add the desired module and my runbook wasn’t complaining anymore 🙂

Connection Problems to a Secure Service Fabric Cluster

To be able to connect to a secure Service Fabric Cluster via PowerShell, you need to import the certificate specified into your personal certificate store. Otherwise an Exception will be thrown. Unfortunately the Exception does not point into the right direction 🙁

So in case you get an Exception like this

Connect-ServiceFabricCluster : An error occurred during this operation. Please check the trace logs for more details.
At line:1 char:1
+ Connect-ServiceFabricCluster -ConnectionEndpoint xyz-sf-de …
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Connect-ServiceFabricCluster], FabricException
+ FullyQualifiedErrorId : CreateClusterConnectionErrorId,Microsoft.ServiceFabric.Powershell.ConnectCluster

you need to import the certificate with its private key (*.pfx) into the personal certificate store of the PC you are running PowerShell on.

 

Specifying -verbose for PowerShell will print additional information, that does not help a lot.

PS C:\WINDOWS\system32> Connect-ServiceFabricCluster -ConnectionEndpoint xyz-sf-dev.northeurope.cloudapp.azure.com:19000 -X509Credential -FindType FindByThumbprint -FindValue xyz -StoreLocation CurrentUser -StoreName My -ServerCertThumbprint xyz -Verbose
VERBOSE: System.Fabric.FabricException: An error occurred during this operation. Please check the trace logs for more
details. —> System.Runtime.InteropServices.COMException: Exception from HRESULT: 0x80071C57
at System.Fabric.Interop.NativeClient.IFabricClientSettings2.SetSecurityCredentials(IntPtr credentials)
at System.Fabric.FabricClient.SetSecurityCredentialsInternal(SecurityCredentials credentials)
at System.Fabric.Interop.Utility.<>c__DisplayClass25_0.<WrapNativeSyncInvoke>b__0()
at System.Fabric.Interop.Utility.WrapNativeSyncInvoke[TResult](Func`1 func, String functionTag, String
functionArgs)
— End of inner exception stack trace —
at System.Fabric.Interop.Utility.RunInMTA(Action action)
at System.Fabric.FabricClient.InitializeFabricClient(SecurityCredentials credentialArg, FabricClientSettings
newSettings, String[] hostEndpointsArg)
at Microsoft.ServiceFabric.Powershell.ClusterConnection.FabricClientBuilder.Build()
at Microsoft.ServiceFabric.Powershell.ClusterConnection..ctor(FabricClientBuilder fabricClientBuilder, Boolean
getMetadata)
at Microsoft.ServiceFabric.Powershell.ConnectCluster.ProcessRecord()
Connect-ServiceFabricCluster : An error occurred during this operation. Please check the trace logs for more details.
At line:1 char:1
+ Connect-ServiceFabricCluster -ConnectionEndpoint xyz-sf-de …
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Connect-ServiceFabricCluster], FabricException
+ FullyQualifiedErrorId : CreateClusterConnectionErrorId,Microsoft.ServiceFabric.Powershell.ConnectCluster

Need users in your dev environment?

Often, you’ll need some users with data like picture and manager in your new development environment. Since you usually recycle your dev AD, this doesn’t happen frequently. But if you have to set up a new domain, you’ll want testusers with data.

I don’t want to search again, because I found a great resource for creating users here: http://mrhodes.net/2011/10/25/adding-285-contoso-users-with-pictures-to-your-development-environment-active-directory/

Have fun with PowerShell

Create the default groups via PowerShell

If your site is missing the three default groups “Visitors”, “Members” and “Owners”, you can create them easily with PowerShell or the Object Model.

 

Update to the SharePoint Solution Deployer

A new version is out. If brings some great new extensions (two of them are from me 🙂 )

v5.0.4.6440 (2015-04-04)

  • New: All extensions added: Blocked file extensions, content type hub, custom crawl connector, features, logging configuration, managed metadata, re-ghost, search schema, secure store, site structure, CSOM extensions for files and 2013 workflows
  • Updated: SharePointVersions.xml
  • Updated: Typos in comments fixed and some code clean-up
  • First release based on GitHub repository

Grab your version from http://spsd.codeplex.com

The SharePoint Solution Deployer

Deploying Solutions can be a …. (fill in as you wish).

The SharePoint Solution Deployer offers a great opportunity to writing your own scripts. The existing functionality should match your needs to deploy SharePoint Solutions. If not, the “framework” can be extended with custom Extensions or simple PowerShell code.

I’ve written two Extensions, which let you enable and disable features upon deployments and reset files to their site definitions (aka ReGhost).

To be able to have different URLs for your dev-machine, staging and production farms, simply create additional XML-files and configure URLs there. The XML-file needs to be named with the hostname of the server, where you want start the deployment.

Example

The example shows two files within the Environment subfolder.

Default XML Configuration file (Default.xml)

 Hostname.xml

The script will look if there is any XML file with the name “hostname.xml”

That’s it.

You can start the deployment with e.g. “Redeploy.bat” from the Rootfolder, no matter which farm you are on.

Use a XML-file for configuration in PowerShell scripts

Time for some PowerShell!

Almost every PowerShell script need some configuration parameters. With this post I want to show one way, there are others ;-), to parse a config file in XML format and use the values later.

The solution I’m going to show to you contains three files. A PowerShell script, a XML configuration file and a helper PowerShell file that contains a function to parse the config file.

PowerShell XML config files

The config file contains

The helper function to parse the configuration file looks like this

And finally the main script, that will reference the helper function, call it and use the values.

Summary: Store configuration settings in a XML file and use the values in PowerShell script.

Start / Stop SharePoint Services via PowerShell

If you have installed SharePoint on your workstation, you might want to start the services only in case of active development. Otherwise the services consume memory and other resources.

The PowerShell script in this post will allow you to easily start and stop all required services for a local SharePoint Installation.

image

It will detect if you’ve installed SharePoint 2007/WSS, SharePoint 2010 or SharePoint 2013. Just copy the code below to a file, name it StartStopSharePoint.ps1 (yes, very creative :-)) and call it from a PowerShell (you don’t need the SharePoint Management PowerShell).

$SharePointV3Services = ('SQLSERVERAGENT','MSSQLSERVER','W3SVC','SPWriter','SPTrace','SPTimerV3','SPAdmin','OSearch','DCLoadBalancer','DCLauncher')
$SharePointV4Services = ('SQLSERVERAGENT','MSSQLSERVER','W3SVC','SPSearch4','OSearch14','SPWriterV4','SPUserCodeV4','SPTraceV4','SPTimerV4','SPAdminV4','FIMSynchronizationService','FIMService','DCLoadBalancer14','DCLauncher14')
$SharePointV15Services = ('SQLSERVERAGENT','MSSQLSERVER','W3SVC','SPSearchHostController','OSearch15','SPWriterV4','SPUserCodeV4','SPTraceV4','SPTimerV4','SPAdminV4','FIMSynchronizationService','FIMService','DCLoadBalancer15','DCLauncher15')

$Services = $SharePointV3Services
$version = 12
# check for SharePoint 2010
$hive = get-ItemProperty "hklm:\SOFTWARE\Microsoft\Shared Tools\Web Server Extensions\14.0"
if ($hive -eq $null)
{
    if ((get-ItemProperty "hklm:\SOFTWARE\Microsoft\Shared Tools\Web Server Extensions\15.0" SharePoint).SharePoint -eq 'Installed')
    {
        $version = 15
        $Services = $SharePointV15Services
    }
}
else
{
    if ((get-ItemProperty "hklm:\SOFTWARE\Microsoft\Shared Tools\Web Server Extensions\14.0" SharePoint).SharePoint -eq 'Installed')
    {
        $version = 14
        $Services = $SharePointV4Services
    }
}

Write-Host -ForegroundColor Green 'SharePoint Version' $version 'found'
Write-Host -ForegroundColor Yellow 'Press'
Write-Host -ForegroundColor Green '1' -NoNewline
Write-Host -ForegroundColor Yellow ' to start SharePoint Services'
Write-Host -ForegroundColor Green '2' -NoNewline
Write-Host -ForegroundColor Yellow ' to stop SharePoint Services'
Write ''

function StartSharePoint($Services)
{
    Write-Host -ForegroundColor Yellow ('Starting ' + $Services.Length + ' services')
    foreach ($serviceName in $Services)
    {
        $service = Get-Service $serviceName -ErrorAction SilentlyContinue 
        if ($service)
        {
            $startMode = (get-wmiobject win32_service | where-object {$_.Name -eq $serviceName}).StartMode
            if (($service.Status -ne 'Running') -and ($startMode -ne 'Disabled'))
            {
                Write-Host -ForegroundColor Green ('Starting "' + $service.DisplayName + '"')
                Start-Service $serviceName
            }
        }
        else
        {
            Write-Host -ForegroundColor Red ('Service "' + $serviceName + '" does not exist')
        }
    }
}

function StopSharePoint($Services)
{
    Write-Host -ForegroundColor Yellow ('Stopping ' + $Services.Length + ' services')
    for($i = ($Services.Length - 1); $i -gt -1; $i--)
    {
        $serviceName = $Services[$i]

        $service = Get-Service $serviceName -ErrorAction SilentlyContinue 
        if ($service)
        {
            $startMode = (get-wmiobject win32_service | where-object {$_.Name -eq $serviceName}).StartMode
            if ($service.Status -ne 'Stopped')
            {
                Write-Host -ForegroundColor Green ('Stopping "' + $service.DisplayName +'"')
                Stop-Service $serviceName -force
            }
            else
            {
                Write-Host -ForegroundColor Green ('"' + $service.DisplayName + '" is already stopped')
            }
        }
        else
        {
            Write-Host -ForegroundColor Red ('Service "' + $serviceName + '" does not exist')
        }
    }
}

function UserInput($strMsg, $intStyle)
{
  #$strMsg: Message displayed on the console sreen
  #$intStyle: User Input Style:
    #1 = Read-Host (Multiple characters, require to press Enter);
    #2 = $host.ui.rawui.readkey() (Single character, do not require to press enter)
  switch($intStyle)
  {
    1 { $strInput = Read-Host $strMsg ; $host.ui.rawui.foregroundcolor = $Global:fgColor ; return $strInput }
    2 { Write-Host $strMsg; $strInput = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown"); return $strInput}
  }
}

$userInput = UserInput "Enter Choice" 2
switch ($userInput.VirtualKeyCode)
{
    49 { StartSharePoint($Services) }
    50 { StopSharePoint($Services) }
    default { Write-Host -ForegroundColor Red 'Press "1" or "2"' }
}

Hint: In case you haven’t set the Script-Execution-Policy yet, you will be prompted to do so. –> Using the Set-ExecutionPolicy Cmdlet

Happy Coding!

Use Powershell ISE for SharePoint 2010

To be able to use the ISE for SharePoint, you can configure it to load the SharePoint cmdlets automatically.

Scot Hillier wrote a great article about it. Read “Setting up PowerShell ISE for SharePoint 2010”.

If you only want to use the SharePoint cmdlets once, you can register them with this two lines:

If ((Get-PSSnapIn -Name Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue) -eq $null )
{ Add-PSSnapIn -Name Microsoft.SharePoint.PowerShell }

Mastering your Hyper-V R2 Core Server

If you like – and use – Hyper-V is out of scope of this post. So let’s assume you have a Hyper-V core installation, as it is free and works great 🙂

Microsoft® Hyper-V™ Server 2008 R2 is a stand-alone hyper-visor based virtualization product which includes Live migration.

Download: http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=3512 (about 1GB)

OK. That was the marketing part.

Many people have great respect for a server, which has no GUI. At least not the way we know “Windows Servers”.

Well, at least for managing your VMs, there are some tools out there. One of them is the PowerShell Management Library for Hyper-V, available on CodePlex. It will give you great control over VMs on your server. And… it has a GUI (kind of), which can be started with “Show-HyperVMenu”:

image

Starting, Stopping and changing the configuration is now possible, without using the Hyper-V Management Console.

The module for PowerShell can be installed by calling a batch file. It works smooth, and does what is needed to manage Hyper-V via PowerShell.

get-command -module HyperV will show all available commandlets. As always (with PowerShell), a get-help commandname shows some help for the commandlet.

Update July 2012

The command for showing the GUI above is “Show-HyperVMenu”

How To install SharePoint 2010 prerequisites automatically

SharePoint 2013:

If you want to install the prerequisites for SharePoint 2013, see here: Installing SharePoint 2013 Prerequisites Without an Internet Connection

SharePoint 2010:

Don’t leave if you read “Powershell” and think “Oh my. Why does it take Powershell to do this?”. Powershell is easy to use and a great tool for this task.

This post is about installing all required components that are needed for a SharePoint 2010 installation (Hardware and software requirements (SharePoint Server 2010)).

So what are we going to to?

  1. Download required software
  2. Create a Powershell script to install the requirements
  3. Install required software

Download required software

The advantage of downloading the required components prior installing SharePoint is, that we can use the downloaded bits on many servers. The size of all these components is about 387 MB. So even if you have a fast internet connection, it might be worth downloading them.

A Powershell script for downloading all required software can be downloaded here: http://autospinstaller.codeplex.com/releases/view/44442

When you start the script, it will ask where you want the downloaded files to be saved.

 image

I’ve copied the content of the SharePoint 2010 Installation bits to a local folder. e.g. C:\Install\SP2010Bits

Then the folder for would be c:\Install\SP2010Bits\PrerequisiteInstallerFiles

Create a Powershell script to install the requirements

A Powershell script in the Rootfolder of the SharePoint bits will install the required software. Create a new file “c:\Install\SP2010Bits\InstallPrerequisites.ps1”. The content of the file would be

So you have the SharePoint 2010 Bits in a folder. In the same folder is the install script, and in a subfolder “PrerequisiteInstallerFiles” all requirements.

image

Install required software

Just run the script from within Powershell 🙂

image

Now you are ready to install SharePoint 2010.

If you get an exception like this, set the execution policy “Set-ExecutionPolicy RemoteSigned“ in a Powershell window.

File C:\install\SP2010Bits\InstallPrerequisites.ps1 cannot be loaded because the execution of scripts is disabled on this system. Please see "get-help about_signing" for more details.

At line:1 char:27

+ .\InstallPrerequisites.ps1 <<<<

    + CategoryInfo          : NotSpecified: (:) [], PSSecurityException

    + FullyQualifiedErrorId : RuntimeException