PowerShell: Test-IsAdmin

Scriptimus PowerShell Banner

Sometimes I only want a PowerShell function to run only if the user has local admin rights. This can be tested for by looking for the admin token.

Here’s a function I use.

Function Test-IsAdmin {

 $user = [Security.Principal.WindowsIdentity]::GetCurrent();
 (New-Object Security.Principal.WindowsPrincipal $user).IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator) 

I then call the function in my code using this snippet

 If (!(Test-IsAdmin)) {
 Write-Warning "This script needs admin rights to run!!!"
 $HOST.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") | OUT-NULL



Technical info on MSDN here.

Remember, for a script or module you could use the #Requires statement but this wont work in a function.

#Requires -RunAsAdministrator 


Posted in PowerShell | Tagged , , | Leave a comment

Testlab: HP ProLiant MicroServer Gen8 G1610T

Once your training evolves to enterprise level, you’ll need enterprise level hardware to simulate real world test scenarios. Let’s face it, corporate IT training is usually restricted to a privileged few so if you want to get on, get your own kit, get training, get certified, get a new job and get paid!

In September, I upgraded my home TestLab by purchasing a HP ProLiant MicroServer Gen8 G1610T. I was excited then by all the talk about the new Gen 9 servers but also understood that realistically there was not going to be a Gen 9 MicroServer any tine soon.


Now in May 2015, HP have dropped the price of the G1610T by half and are also offering a a cashback deal. (Perhaps because they’re about to release the Gen9?) So I just bought a second one.

Here’s the spec and cost of my first Gen8 server.

Intel BX80637E31240V2 Xeon Quad-Core Processor 3.4 GHz LGA1155 Socket 8 MB L3 Cache 69 Watt



2 of Samsung 840 EVO 250GB 2.5 inch Basic SATA Solid State Drive



Kingston Technology KVR1333D3E9SK2/16G – Kingston ValueRAM 16GB (2x8GB) Memory Kit 1333MHz DDR3 ECC 240-pin Unbuffered DIMM



HP G1610T 150W PS ProLiant Gen8 Micro Server



This spec

For the new server, this time I only bought memory and decided to use existing hard drives and try the Celeron CPU out to see how far I get with it before I run into issues. I’ll post back with my judgement on the Celeron CPU running a basic lab at some point.

Here’s  the spec

HP ProLiant Gen8 G1610T MicroServer


£119.99 after cashback
Kingston 16GB 1333MHz DDR3 ECC CL9 DIMM (Kit of 2)



In my opinion, for a Windows Server 2012 R2 Hyper-V TestLab, I wouldn’t recommend purchasing this unless you get a bargain. For one thing, it has BIOS not UEFI so it will not run Generation 2 VM’s. I’m not saying don’t buy it(I think it’s a really great server), I’d just consider more up to date hardware.

It was my plan to buy one of the new NUC boxes but I’m just waiting for Samsung to release their super fast M.2 NVMe SSD.

Anyway, I upgraded the memory before first boot without any issues. Just pop off the lid and remove the old stick.


The memory is detected and tested auto’magic’ly on the first boot.


I had this great plan of booting VMware from MicroSD so ran out and bought these 2 bad boys after checking the official guidelines from HP.


It didn’t work and I’m currently at a loss to understand why the card was not recognized so further research is in order. There’s a post of people having similar issues here.


I had to open the case again to get the card back out which is something which could be improved upon in the next gen. I suppose in the meantime I could boot from USB(Done that. Sigh!).

Next I had the bright idea of using some of the crappy old drives I had lying around. I decided to use one of my 250Gb SATA drives as a boot drive and use the others in a pool.


Windows Server 2012 R2 installed OK using Intelligent Provisioning but when I tried tab completion in PowerShell for the first time the system took 10 minutes to complete that task. I had a similar delay when I tried to open Disk Manager. Then I had the idea of putting all the drives in at once and using the Smart Storage Administrator (It’s in Intelligent Provisioning)tool to examine the drives.


After reviewing the hard drives, I decided to remove all the SATA 2 drives and just stick with the SATA 3 1TB drive. After rebuilding Server 2012 R2 again using IP, the tab completion issue and other issues were gone. Lesson learned. I’ll stick the SATA 2 drives back in the old N40 server for my upcoming FreeNAS lab tests.

Finally, here’s the great link to the Home Server Show Forum that really helped me demystify what hardware was compatible.


Posted in Testlab | Tagged , , | 2 Comments

Managing DSC Resources in PowerShell Desired State Configuration (DSC)


PowerShell Desired State Configuration (DSC) Resources are an evolved type of function usually created by experienced PowerShell coders. Resources are at the very core of DSC and contain the code required to perform the actual configuration tasks in your deployments.

My first post was how to use DSC. My second post was about what DSC is, this post is more of a where to find and discover resources.

In my previous post, I used a DSC Resource called File and executed it a number of ways to manipulate a text file. You can view its syntax in the console by using the Get-DSCResource cmdlet with the -Syntax switch.


Built in Resources

DSC comes with a small number of built-in Resources for configuring files and folders, roles and features, security groups, registry settings, environment variables, and services and processes. You can view these built in resources by typing Get-DSCResource. This screenshot of my laptop, this is an example of what you would see with the default setup.


You can find more information on these build-in resources here: Built-In Windows PowerShell Desired State Configuration Resources

Powershell Team Resources

From December 2013 to February 2015 the PowerShell team released a number of DSC Resources called the DSC Resource Kit. These contained a number of PowerShell modules that contained DSC resources and example configurations. They were published to Technet in the PowerShell gallery.

These were great resources but were by no means complete. They were starter modules intended as guidance and working examples to help the community develop their own resources.

Sadly the PowerShell team have stopped publishing the resource kit at wave 10. They are however, still releasing new and updated resources via the PowerShell Gallery and recommend that you use PowerShellGet (in WMF 5.0) to find them.

Microsoft propose naming standards for publicly shared resources. They use the x prefix that stands for ‘experimental’. Microsoft Resources

No refunds!

These resources are offered freely but without any support. If you find any issues etc you can post a request on Microsoft Connect but don’t hold your breath. I posted a request last September that has had no response. Bugs however are answered slightly quicker like this one. DSC: xIPAddress IP detection issue I’ve still not seen a fix though. In the end I just fixed the bug myself and renamed the resource to a comunity resource using the standards Microsoft suggest at the bottom of this page.

Community resources

Speaking of which, you can develop your own resources or download them from the community. I’ll be releasing my own resources shortly in a kit to help automate the building of the Windows Server 2012 R2 Test Lab Guide.

ScriptimusExMachina Resources

Microsoft suggest prefixing your own resources with ‘c’ for community. If you do build your own resource then the PowerShell Team have posted the really helpful PowerShell DSC Resource Design and Testing Checklist on their blog. Thanks guys!

Corporate or private resourses.

You could create your own internal corporate standard. Eg. ‘e’ for enterprise. This would help to indicate that these are private and should not leave your business environment. But then again, that’s your own business.

Installing resources from the internet.

The first thing to do is (after a virus/malware scan) right-click and unblock the archive before accessing it as it came from the internet. If not then the contents will also be still blocked and you’ll have fun unblocking each of the files in turn.


As always never put code from the internet into your production environments. Use the online resources as examples to help develop your own code.

Unpack the contents into the folder C:\Program Files\WindowsPowerShell\Modules\

Then use Get-DSCResource to see if you can now access them. If you can still only see the built in resources then it’s likely that you will need to download and install Hotfix KB 2883200 (Windows 8.1 and Windows Server 2012 R2 General Availability Update Rollup)

This is the last of the basic topics that I’ll be posting on DSC.  Next I’ll share the resources that have helped me learn DSC and then I’ll post details of the hurdles and gotcha’s I came across when trying to build my own resource.

Posted in Deployment, Desired State Configuration, DSC, PowerShell | Tagged , , , , | 3 Comments

PowerShell: Inside Desired State Configuration (DSC) – Get,Set and Test


Today I’m going to continue explaining the fundamentals of PowerShell Desired State Configuration (DSC). Yesterdays post focused on running DSC but today, I’m going inside DSC to demonstrate DSC’s indempotance nature and also the Get, Set and Test functions. I’ll do this by walking through the Script DSC Resource.


When I first heard about PowerShell DSC I was told it was idempotent. I joked well it can happen to anybody(boom-boom!). But then I actually looked up the term and discovered it meant “an operation that will produce the same results if executed once or multiple times”

In fact, if you run a DSC script it will TEST the configuration first. If the configuration evaluates as non compliant then it will SET the configuration. Running the script/configuration/resource again will do nothing further as the configuration will now evaluate as compliant.

Inside the DSC Resources.

This is a DSC Resource I wrote called STMS_cAuthoriseDhcpServer. It has 3 functions that are common in all DSC Resources. Get-TargetResourse, Set-TargetResourse and Test-TargetResourse.


These functions must all exist and have the names given above.

Example Configuration.

OK let’s look at todays script.

Configuration HelloWorld {
    Script Demo
        GetScript = {
            $File = 'C:\ScriptimusExMachina\DSCHelloWorld.txt'
            $Content = 'Hello World!'
            $Results = @{}
            $Results['FileExists'] = Test-path $File
            $Results['ContentMatches'] = Select-String -Path $File -SimpleMatch $Content -Quiet

        SetScript = {
            'Hello World!' | Out-File C:\ScriptimusExMachina\DSCHelloWorld.txt
        TestScript = {
            $File = 'C:\ScriptimusExMachina\DSCHelloWorld.txt'
            $Content = 'Hello World!'

            If ((Test-path $File) -and (Select-String -Path $File -SimpleMatch $Content -Quiet)) {
                Write-Verbose 'Both File and Content Match'
            Else {
                Write-Verbose 'Either File and/or content do not match'


It’s another Hello World DSC configuration that does exactly the same as yesterdays script, but this time, I’m using a built in resource called Script.

Just as I did yesterday, I paste the configuration into the console(for testing) and execute it to create my MOF file.


Just as before, launching it creates a text file with the contents “Hello World!”


The Script Resource

We can explore a DSC resource by using the Get-DSCResource cmdlet. The syntax parameter shows the actual code that we can use in our configuration. It is a common practice to just copy and paste the syntax into a code editor.


This resource will hold 3 script blocks. The Get, Set and Test code.


This code block returns a hashtable and is run only when you use the Get-DSCConfiguration cmdlet to view the values of the current state. It does not affect the execution of DSC in push or pull modes.

GetScript = {
    $File = 'C:\ScriptimusExMachina\DSCHelloWorld.txt'
    $Content = 'Hello World!'
    $Results = @{}
    $Results['FileExists'] = Test-path $File
    $Results['ContentMatches'] = Select-String -Path $File -SimpleMatch $Content -Quiet



This code block applies the configuration when DSC is executed. It contains the code required to return the configuration to the desired state. Within this section you can call functions or any available cmdlets needed.

SetScript = {
    'Hello World!' | Out-File C:\ScriptimusExMachina\DSCHelloWorld.txt


This code block evaluates the configuration and returns a Boolean value of either True or False. It is executed when either Start-DSCConfiguration Test-DSCConfiguration are launched. During a DSC configuration process, this function is run first and if it evaluates as true then the Set is launched immediately.

TestScript = {
    $File = 'C:\ScriptimusExMachina\DSCHelloWorld.txt'
    $Content = 'Hello World!'

    If ((Test-path $File) -and (Select-String -Path $File -SimpleMatch $Content -Quiet)) {
        Write-Verbose 'Both File and Content Match'
    Else {
        Write-Verbose 'Either File and/or content do not match'



The power of DSC is in these 3 little functions. They represent good standards that could be applied to any kind of infrastructure scripts.

Posted in Deployment, Desired State Configuration, DSC, PowerShell, Scripting | Tagged , | Leave a comment

PowerShell: Desired State Configuration – Getting started.


By now most people will have heard about the Windows PowerShell Desired State Configuration(DSC), the incredibly powerful configuration management platform that comes with PowerShell 4.0. This post will describe the feature in its most basic form and assume you’re new to the topic(or have been living under a rock). This should give you an overview and basic understanding of how PowerShell DSC fundamentally works. From then, I’ll post further and share how I’ve been using DSC to control my Lab environments.

What’s it all about then?

DSC is a management platform in Windows PowerShell that essentially just runs PowerShell scripts in a very clever manner, allowing you to push a configuration to a computer. You can do pretty much anything in PowerShell and as DSC runs on top of PowerShell you have even more power with DSC. Also, the amazing thing is you don’t even need to learn scripting to use it, you just edit a text file.

PowerShell DSC is really cool and the next big thing in the world of deployment. Moving forward I can see DSC replacing (or augmenting) Group Policy, building local and cloud based servers/hydration kits, removing malware/deploying software, etc.

Today’s post will demonstrate how to use PowerShell DSC in ‘Push’ mode by authoring a DSC Configuration using ‘Declarative Syntax’ to create a text file with the words “Hello World” and then ensure that the file and its content will remain compliant.

The same basic process will be used in further posts to build an entire server and domain PoC testlab. The power of PowerShell Desired State Configuration(DSC) is practically limitless.

So is there a script coming any time soon?

Indeed! Enough talk, here’s the Hello World Script. It’s written in DSC declarative syntax and uses a DSC Resource called File to create a text file.

configuration HelloWorld {
 param ()
 Node Localhost 
   # Create a Test File
   File CreateTestFile
     Ensure          = "Present"
     DestinationPath = "C:\ScriptimusExMachina\example.txt"
     Contents        = "Hello World."
     Type            = "File"

# Create MOF Files
HelloWorld -OutputPath C:\ScriptimusExMachina\HelloWorld

# Start DSC Configuration
Start-DscConfiguration -Path C:\ScriptimusExMachina\HelloWorld -ComputerName Localhost -Verbose -Wait

I still don’t get it?

What we’re trying to do here is generate a folder that contains a configuration file in MOF format.

Erm , I’m still not getting it. This MOFF fellow, is this the guy Darth Vader choked or the old guy played by Peter Cushing?

Grand Moff Tarkin. (Not to be confused with a MOF file in PowerShell DSC)

Erm, neither. A MOF is just a text file in Managed Object Format (MOF). We’re going to use this MOF file to apply a configuration to our host computer. We don’t actually need to learn how to write a complex MOF file. We’re going to use the Configuration in the script above to create the MOF file for us.

For demo purposes we paste the Configuration into the console.


The Configuration works like a Function and has 3 parameters InstanceName, OutputPath and ConfigurationData. Ed Wilson (The Scripting Guy) does a great job of describing these here.


We now run our HelloWorld Configuration in its simplest form.

HelloWorld -OutputPath C:\ScriptimusExMachina\HelloWorld


As you can see, it creates a folder with the same name as our Configuration with a .MOF file inside. The MOF filename is the same as the target hostname specified in the Hello world configuration earlier. If you had multiple hostnames in your configuration then you would have one for each host.


What this means is that when the configuration is applied, each MOF (one for each machine) file will be applied. In this case however, we’re just using Localhost.

Just do it already!

We use this command to start the DSC configuration.

Start-DscConfiguration -Path C:\ScriptimusExMachina\HelloWorld -ComputerName Localhost -Verbose -Wait

The Configuration is applied using the Start-DscConfiguration cmdlet, pointing it to the folder path of our MOF files. If you had multiple hosts configured then you could just apply one by name by using the ComputerName parameter as shown in the example. Using the Verbose and Wait Parameters causes DSC to output its data in real time as shown below.


Walking through the syntax used in the script earlier. First we ensure that our configuration is present. We could use Absent to delete a file or folder.

Ensure          = "Present"

We specify the name and path of the file that we’re going to create. The type could also be a folder instead.

DestinationPath = "C:\ScriptimusExMachina\example.txt"
Type            = "File"

Here we ensure that its contents are a specific string.

Contents        = "Hello World."

Looking in the folder, we have a new text file with the desired content.


Now that’s PowerShell DSC in its simplest form.

We can test that our Configuration is compliant using the Test-DSCConfiguration CmdLet. This will return a Boolean response.


Watch what happens when I change the content of the file.


Now I can use Restore-DscConfiguration to re-apply the configuration.


This is made possible because the MOF file that was applied last has been copied to C:\Windows\System32\Configuration\Current.mof. You could use Restore-DscConfiguration to re-apply the configuration without the source.Configuration

By using the source I could also re-apply the configuration by using the Start-DscConfiguration cmdlet again.


You’ll see that this time, by not using the Verbose and Wait Parameters that DSC is showing me that the process is running as background Job.

You can retrieve the job as usual.


Finally, you can use the Get-DscConfiguration cmdlet to view the current configuration.


In future posts I’ll be discussing more complex configurations so keep reading.

Posted in Desired State Configuration, PowerShell | Tagged , | 2 Comments

PowerShell: New-Password Function

Scriptimus PowerShell Banner

OK, so I’ve been off the grid for a while now. But that doesn’t mean I’ve not been busy. Quite the opposite in fact. I’ve taken a year out from work on paternity with my baby Son. During this time, I did a lot of training in my lab developing new skills and solidifying other more fundamental skills. I’ve also passed a couple of certified exams and have built a new lab from a new HP Micro-server that I juiced up. I’m currently planning to take the MCSA: Server 2012 R2 exam and have been training in my lab and doing a lot of PowerShell DSC based automation. Hopefully I’ll be able to share some if not all of this knowledge and experience soon. I thought it best to return with a simple post so here goes.

During my time off I wrote a simple function to generate a password from random characters. I posted it yesterday here in the Microsoft Script Center Script Repository . Here’s a quick screenshot demo:


And here’s a simplified version for discussion.

Function New-Password {








        If ($Uppercase) {$CharPool += ([char[]](65..90))}
        If ($LowerCase) {$CharPool += ([char[]](97..122))}
        If ($Numeric) {$CharPool += ([char[]](48..57))}
        If ($Symbolic) {$CharPool += ([char[]](33..47))
                       $CharPool += ([char[]](33..47))}

        If ($CharPool -eq $null) {
            Throw 'You must select at least one of the parameters "Uppercase" "LowerCase" "Numeric" or "Symbolic"'

        (Get-Random -InputObject $CharPool -Count $length) -join ''


The only issue with this was working out each of the character types. Fortunately I learned, through testing, that you could return a series of ASCII characters by indexing them.


PowerShell Characters

For example, this line of code places the lowercase characters a-z in a variable (really a string type object) called $L.

$L = ([char[]](97..122))

PowerShell Characters LowerCase

Here you add 92 characters in turn to a string object called $CharPool.

$CharPool += ([char[]](65..90))
$CharPool += ([char[]](97..122))
$CharPool += ([char[]](48..57))
$CharPool += ([char[]](33..47))
$CharPool += ([char[]](33..47))

Yes, I really counted them!

PowerShell Count Characters

Next, I needed to work out how to get a number of random characters from the pool so I used the Get-Random cmdlet.

$CharPool = ([char[]](97..122))
Get-Random -InputObject $CharPool -Count 5

The problem with this though is that each of the characters are on a new line.


Then I remembered the -Join operator.

(Get-Random -InputObject $CharPool -Count 5) -join ''

PowerShell Get-Random Join


Posted in PowerShell | Tagged , , | 10 Comments

SCCM PowerShell: Connect to SCCM Function



Today’s post is another time-saver function I wrote to connect to SCCM. Again, it is designed to eliminate the need to hard code the module path and/or the SCCM primary site. It allows me to just type Connect-SCCM to import the module then enter to the SCCM PSdrive.

Like my MDT function this one locates the install path from the registry to help discover the module location. It will then detect the SCCM PS drive automagically and set the location to it.

I’ve uploaded it to the Technet script repository here and again below is the simplified version.

Function Connect-SCCM { 

    If (!(Get-Module ConfigurationManager)) { 

        [String]$SCCMInstall = ((Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\ConfigMgr10\Setup').'UI Installation Directory') 

            Import-Module ($SCCMInstall +'bin\ConfigurationManager.psd1') -Scope Global 


    Set-Location ((get-psdrive -PSProvider CMSite).Name+":") 

Posted in MDT 2010, MDT 2012, MDT 2013, PowerShell | Tagged , , | 1 Comment