Saturday, October 27, 2018

There's always a way...

I teach my classes that there's always more than one way to do almost anything. This week was a nice reminder of how true that is.

The client had a legacy script that scans their client's AD attached computers. One small thing this script does is to determine the Domain Functional Level and whether the domain is still in mixed mode.

The 'old' script we were looking at was a very long, comment-free VBS script using LDAP to get the Domain Object in the AD to get the values for those two attributes to determine the domain level. You might think you could convert that horrid VB code into a simple Get-ADDomain, pick out the two properties.

Sadly, that does not work. The Get-ADDomain cmdlet returns a number of properties that represent the attribute values inside the AD.  But not all!

Here is a screenshot of LDP.EXE showing the domain object and two properties inside my AD:



As you can see, the domain object has two attributes/properties (msDS-Behavior-Version and ntMixedDomain. But Get-ADDomain does not return those properties, as you can see here:


The solution, however, is pretty easy. Get-ADDomain returns an object with the Distinguished Name of the domainDNS object. That object represents the domain inside the AD and it is that object which has the needed properties. So, use Get-ADDomain to get the Domain object's Distinguished Name (DN), then use Get-ADObject to get the object whose identity is that DN. It looks like this:



An interesting thing is that some AD objects, like the domainDNS object, have attribute names that contain a hyphen, eg the msDS-Behavior-Version attribute. This can confuse PowersShell's parser. So the solution is to enclose the property names in braces, as you can see in the final line of the snippet above. An obscure feature of PowerShell that in this case is useful.

All in all, I'd like to think Jimmy Andersen would be impressed. Well, a bit anyway!




Thursday, October 04, 2018

Installing RSAT tools

I've been installing 1803 (and for reasons I can not explain, 1709)  on a bunch of workstations - but needed the RSAT tools. I HATE having to use the GUI - so here's a PowerShell script:

# Install-RSATTools.PS1 # Thomas Lee - doctordns@gmail.com # 1. Get Windows Client Version and Hardware platform $Key = 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion' $CliVer = (Get-ItemProperty -Path $Key).ReleaseId $Platform = $ENV:PROCESSOR_ARCHITECTURE "Windows Client Version : $CliVer" "Hardware Platform : $Platform" # 2. Create URL for download file # NB: only works with 1709 and 1803. $LP1 = 'https://download.microsoft.com/download/1/D/8/'+ '1D8B5022-5477-4B9A-8104-6A71FF9D98AB/' $Lp180364 = 'WindowsTH-RSAT_WS_1803-x64.msu' $Lp170964 = 'WindowsTH-RSAT_WS_1709-x64.msu' $Lp180332 = 'WindowsTH-RSAT_WS_1803-x86.msu' $Lp170932 = 'WindowsTH-RSAT_WS_1709-x86.msu' If ($CliVer -eq 1803 -and $Platform -eq 'AMD64') { $DLPath = $Lp1 + $lp180364} ELSEIf ($CliVer -eq 1709 -and $Platform -eq 'AMD64') { $DLPath = $Lp1 + $lp170964} ElseIf ($CliVer -eq 1803 -and $Platform -eq 'X86') { $DLPath = $Lp1 + $lp180332} ElseIf ($CliVer -eq 1709 -and $platform -eq 'x86') { $DLPath = $Lp1 + $lp170932} Else {"Version $cliver - unknown"; return} # 3. Display the download details "RSAT MSU file to be downloaded:" $DLPath # 4. Use BITS to download the file $DLFile = 'C:\foo\Rsat.msu' Start-BitsTransfer -Source $DLPath -Destination $DLFile # 5. Check Authenticode signature $Authenticatefile = Get-AuthenticodeSignature $DLFile If ($Authenticatefile.status -NE "Valid") {'File downloaded fails Authenticode check'} Else {'Downloaded file passes Authenticode check'} # 6. Install the RSAT tools $WusaArguments = $DLFile + " /quiet" 'Installing RSAT for Windows 10 - Please Wait...' $Path = 'C:\Windows\System32\wusa.exe' Start-Process -FilePath $Path -ArgumentList $WusaArguments -Wait # 7. Get RSAT Modules Get-Module -Listavailable | Where-Object Name -like '*rsat*'

Friday, August 03, 2018

PSReadline V2 Can Break PowerShell Profile Scripts in Latest Insider's RS5 Preview

The Windows Insider programme provides access to the latest pre-release versions of Windows 10 and Windows Server 2019. Earlier this week, Microsoft released a new preview of what is coming with Windows 10 RS5. This build, 17728.1000, contains an updated version of the module PSReadLine. PowerShell uses this module to enable you to, inter alia, set the colours of tokens in the PowerShell command console.

I love this feature, as it allows me to override the default colours that PowerShell uses. One particular issue for me is that the colours can look less good when displaying on some of the lower quality projectors I get stuck with!  One example - the parameter name token is set, by default, to gray. Displaying from my laptop, this has been hard to see at some sites. So I just added this line to my profile:
Set-PSReadlineOption -TokenKind Parameter -ForegroundColor Cyan
Simple and this is highly useful for me ainsome places I teach. However, with the latest release of the RS5 preview, Microsoft has  now included an updated version of PSReadline (2.0 vs 1.2). Taking the new version was done to enable a fix to an accessibility issue. If you run PowerShell after the upgrade, you might see this error when you run PowerShell:


This is both a breaking change and one not described in the release notes. And, if you use Bing or Google to search for Set-PSReadLine, the page at docs.microsoft.com shows the old version of the cmdlet - you need to dive into the actual PSReadLine repository (ie the modules 'source' code!) to discover the answer.

The solution is simple - change that line to:
Set-PSReadLineOption -Colors @{"parameter" = [ConsoleColor]::Cyan}
I've opened issues at docs.microsoft.com, the PsRadline repo and with the Insider's programme, so hopefully going forward this issue is no longer an issue.


Friday, July 20, 2018

My Book Scripts

I saw a comment over on Amazon relating to my last PowerShell book (see Amazon Book Listing) from Long Time Programmer. His comment is that he couldn’t download the code. I wish there was a way I could comment on his comment as there is a way. I’ve put all my scripts up on GitHub!  If you go to https://github.com/doctordns/PowerShellCookbook you can see the scripts there.  Although I have to say some of them – getting the scripts onto GitHub is a work in progress.

As an aside and for background: the publication process at the time this book was published had a few issues.  The web site used to enter content  was literally eating content so we switched over to word at last hour. In doing so, the longer-line scripts ended up broken in the final PDF and thus the published version.

To be helpful to my readers, I’ve slowly retrieved the scripts from inside the VMs and have published them to GitHub, Which is less simple than it sounds and it not yet complete. At present, I’ve ported over the recipe scripts for chapters 1-4, 8, 10, 11 (7 out  of 13). And I hope to have the updates soon.
Please download any of the scripts – and file issues if you find problems.

[Later]
The conversion has been completed and I've created a version 1.0 of the scripts on the GitHub repository. . You can consume the scripts by navigating the GitHub UI or you can take a fork and clone to a local machine. The release mechanism in GitHub provides a zipped up Go to the GitHub Release page and download a .gz or .zip file depending on your tastes. I may do some further tidying up. 

Wednesday, July 18, 2018

Please Buy This PowerShell Conference In A Book

psbook

A couple of months ago, M:Ike Robbins (the tech editor of my last PowerShell book (https://www.amazon.co.uk/dp/B073RP2SNZ/ref=dp-kindle-redirect?_encoding=UTF8&btkr=1), sent me mail about a project that he and a few others were planning. The idea was to develop a PowerShell Conference in a book. Mike invited some of the big PowerShell community members to each contribute one chapter. The proceeds are intended to help the DevOps community. Any royalties are to go towards OnRamp Scholarships with the DevOps Collective. Of course I said yes.

Well – now that book is published to which I have contributed a chapter. You can read about the book and buy it here: https://leanpub.com/powershell-conference-book. The book has an impressive list of contributors and is pretty reasonably priced! Of course, if you are feeling generous, LearnPub is happy to enable you to pay more.

The On-Ram Scholarship is a great cause, bringing new people into the DevOps field. You can read about the scholarship here: https://powershell.org/summit/summit-onramp/onramp-scholarship/

My chapter in the book is entitled ‘A Lap Around .NET’ in which I look at what is .NET and some of the things you can do with it.

Saturday, July 14, 2018

Keeping PowerShell Modules Up To Date

At one time, many (most?) IT Pros did not worry to much about updating PowerShell modules,relying for the most part on whatever cmdlets come with the Application, PowerShell, and/or the OS. But times have changed. With the release of Windows PowerShell 5.1, work on modules both inside and outside Microsoft has not stopped. And a number of modules now have updates that might be useful.

Another big change in the PowerShell world is the movement towards holding these new versions on Repositories that you can access via built-in commands (i.e. Find-Module, Update-Module, etc). The question then becomes what modules need updating? Turns out there is a script or two for that!

The first question is whether you care enough about module updates to worry about dealing with updates, and the side effects of module changes.

As I was writing this article, I encountered an interesting example of this issue. The version of the PSReadline module has been updated  to Version2.0 This version has a breaking change in how you set UI token colours. it took a while to sort out but it drove home to me the need to test new versions and not just update because you can. Unless, I suppose, you like living on the edge.

So how do you tell what modules need updating. And as ever, there’s a script for that ™.

Here is a simple function that looks at all the modules you have on your system (well those pointed to via $env:PSModulePath), and checks to see if that module is available via the PSGallery. For every module the founction returns an object with three properties: the module name, the version on the local system and the version on PSGallery. For modules that do not exist on PSGallery, the script returns a PSGallery version of ‘zero’. Here’s the function:

Function Get-ModuleVersionInformation {

[Cmdletbinding()]
Param()

# Startup
$Start = Get-Date
Write-Verbose 'Get-ModuleVersionInformation'
Write-Verbose 'started at: [$start]'

# Get the modules on the local system
$Modules = Get-Module -ListAvailable -Verbose:$False
Write-Verbose ("{0} modules locally" -f $modules.count)

# For each module, see if it exists on PSGallery
# Create/emit an object for each module with the name,
# and the version number of local and remote versions
Foreach ($Module in $Modules) {
  Write-Verbose "Processing $($module.name)"
  $UpdateHt         = [ordered] @{}    # create the hash table
  $UpdateHt.Name    = $Module.Name     # Add name
  $UpdateHt.Version = $Module.Version  # And local version

try {
#  Find module, and add gallery version number to hash table
    $GalMod = Find-Module $Module.name -ErrorAction Stop
    $Updateht.GalVersion = $GalMod.Version
  }
  # here - find module could not find the module in the gallery
Catch {  
   # If module isn't in the gallery
  $Updateht.GalVersion = [System.Version]::new(0,0) 
  }

# now emit the object
New-Object -TypeName PSObject -Property $UpdateHt

} # End foreach

$End = Get-Date
Write-Verbose "Stopped at: [$End]"
Write-Verbose "Took $(($End-$Start).TotalSeconds) seconds"
  
} # End Function

On my system, the output looks like this:

Psh[Cookham24:C:\foo]> $mods = Get-ModuleVersionInformation
Psh[Cookham24:C:\foo]> $mods

Name                     Version     GalVersion
----                     -------     ----------
Buildlab                 1.0         0.0       
NetCmdlets               16.0.6446.0 16.0.6592.0
ScriptBrowser            1.3.2.0     1.3.1.0   
tfl                      1.0         0.0       
Azure.AnalysisServices   0.5.0       0.5.2     
Azure.Storage            4.1.0       4.3.1     
AzureRM                  5.2.0       6.4.0                      
AzureRM.RedisCache       4.1.0       0.0       
AzureRM.Relay            0.3.1       0.0
 

… Etc.

Loaded with this function you can then do this:

$zero = [System.Version]::new(0,0)
foreach ($mod in $mods) {
  If ($mod.galversion -eq $zero) {
  $msg = "Module [$($mod.name)] does not exist in PSGallery"
  $msg
  continue
  }
  If ($mod.galversion -gt $mod.version){
  $msg = "Module [$($mod.name)] should be updated from v$($mod.version) to v$($mod.galversion)"
  }
  Else {
  $msg = "Module [$($mod.name)] does not need to be updated - current version $($mod.version)"
  }

$msg
} # End foreach

The output, again in my main workstation looks like this:

Module [Buildlab] does not exist in PSGallery
Module [NetCmdlets] should be updated from v16.0.6446.0 to v16.0.6592.0
Module [ScriptBrowser] does not need to be updated - current version 1.3.2.0
Module [tfl] does not exist in PSGallery
Module [Azure.AnalysisServices] should be updated from v0.5.0 to v0.5.2
Module [Azure.Storage] should be updated from v4.1.0 to v4.3.1
Module [AzureRM] should be updated from v5.2.0 to v6.4.0
Module [AzureRM.AnalysisServices] should be updated from v0.6.2 to v0.6.9
Module [AzureRM.ApiManagement] should be updated from v5.1.0 to v6.1.1
Module [AzureRM.ApplicationInsights] should be updated from v0.1.1 to v0.1.4
Module [AzureRM.Automation] should be updated from v4.2.0 to v5.0.1
Module [AzureRM.Backup] should be updated from v4.0.2 to v4.0.6
Module [AzureRM.Batch] should be updated from v4.0.4 to v4.1.1
Module [AzureRM.Billing] should be updated from v0.14.0 to v0.14.3

This leaves me with a bit of work to do – updating PSReadLine, as I discovered did have some unfortunate side effects (and I suspect I am not the only one to have fallen over this issue!).

If I was brave, I could have updated that last script fragment to actually update each of the older modules. Not sure I’m ready for that, just yet…





Saturday, May 19, 2018

Free Cheat Sheets, Revision Aids and Quick References

A cheat sheet is a simple short document, typically 1-2 pages of notes designed to aid your memory.  I discovered an interesting site today, https://www.cheatography.com/. This site has over 2500 cheat sheets for all manner of topics, including Office, Business, Technology, kitchen and garden, travel, and a whole lot more.  The site has 17 cheat sheets relating to PowerShell as well as  35 cheat sheets relating to PHP. The most viewed cheat sheet relates to Regular Expressions (a technology I have yet to master).

The site also enables you to create your own cheat sheets.

Friday, April 06, 2018

Method Chaining–A Neat PowerShell Trick

I discovered an interesting  with PowerShell. It’s known as method chaining. Before explaining it – look at an example:

# c:\foo\testit.ps1
# Test of method chaining
$StringBuilder = [System.Text.StringBuilder]::New()
# Build up string contents
[string] $S1 = Get-ChildItem -Path c:\*.pdf | out-string
# Now build the string
$Null = $StringBuilder.
   AppendLine('Using String Builder as opposed to string concatenation').
   AppendFormat('This uses a cool feature: {0}', 'Method Chaining').
   Append([System.Environment]::NewLine).
   AppendLine('.NET has other "builder" classes operate the same way.').
   Append($S1)
# Output the resultant string
$StringBuilder.tostring()

This produces the following output:

2018-04-06_00-38-27


With Method Chaining, you have an object with methods. You specify the object name (i.e. $StringBuilder) followed by a ‘.’ character. On subsequent lines you specify a method call followed by another ‘.’ character. In this case, I created the $StringBuilder object, then chained several method calls. Each method call added lines to the $StringBuilder object. You end the method chaining by omitting the .’ on the final method in the chain (the directory listing).

I’m not too sure I’d advocate using this. It is an obscure trick of the PowerShell parser and as such might fail my “3:00 in the Morning Test” (if woken at 3:00, could you figure this out before a cup of coffee?). But is pretty cool. Yet another example of how awesome the PowerShell parser is!

Wednesday, March 21, 2018

Code Signing Certificates and PowerShell

When creating PowerShell scripts for distribution, it can be useful to digitally sign the script. This ensures the person getting your code knows it has not changed since you sent it, and can verify you as the person signing the code. If you put code on GitHub, for example, a signature might be a great idea. To do this, you need to have a code signing certificate.

In terms of certificates, you have two main options. You can use your own CA to issue the certificate(s) – or use a public CA. The benefit of the public CA is that their root CAs tend to be fully trusted making it more useful. If you issue your own certs, you may have trouble with other people trusting your code signing certificates.

I have recently obtained a new code signing certificate from DigiCert (https://www.digicert.com). It was really very easy:

1. Open an account and order your cert.

2. Validate you are who you say you are. This involves sending DigiCert some documentation (eg your Passport) to prove you are who you way you are.

3. Do a Skype call, where they watch you sign their Identify Verification and Authorization document.

4. Generate, download, and install the certificate.

The validation process was easy although I had issues with the Skype call, initially. Mainly because I was flat out ill for weeks. Then when I was better, I had some difficulty getting the Skype call going. Entirely my issue, although it has to be said, Digicert support are really very, very, very busy. Between being ill and their overload, it took a bit longer to organise – but today it’s done. I did the call, they saw me sign the form and within an hour or so, the cert was working.

To use the cert to sign something is pretty easy. First you start with the script you want to sign:

# C:\Foo\Certs\Cert1.ps1
Write-Host "I got my cert from DigiCert"

A simple script saved as C:\Foo\Certs\cert1.ps1. To sign it it is simple:

$Cert = Get-ChildItem -Path Cert:\CurrentUser\My\ –CodeSigningCert
Set-AuthenticodeSignature -Certificate $Cert -FilePath C:\Foo\Certs\Cert1.ps1

Once signed, you can verify the signature by using Get-AuthenticodeSignature, like this:

2018-03-21_16-39-30

Very simple and very straightforward. If you, for some reason, have multiple signing certificates then you’d need to adjust call to Get-ChildItem to ensure you get the right certificate.


Friday, February 23, 2018

PowerShell’s $OFS built-in Variable And What It Does

The other day, I was working on converting some C'# to PowerShell. 95% was trivial and almost muscle memory. Then I came to this block of C#

char[] chars = { 'w', 'o', 'r', 'd' };
string string1 = new string(chars);
Console.WriteLine(string1);

The output is:

word

So I initially translated it as:

[char[]] $Chars =  ('w', 'o', 'r', 'd' )
[String $String1 = $Chars
Write-Host $String1

But that produced:

w o r d

The same characters but with spaces between which seemed illogical (at first!). I scratched my head, and did a bit of digging over at Spiceworks, where I was introduced to the $OFS PowerShell Variable. $OFS holds a string, known as the Output Field Separator.   PowerShell uses this character string to separate array elements when it coverts the array to the string, PowerShell has a default value of  ” ”, but you can change at the command line, in a script, or in your Profile. The issue here is that PowerShell is doing the array to string conversion and separates each character in the char array with the separator (“ “). You can read a bit more about this in an old blog post by Jeffrey Snover:

This gave rise to two solutions. The first is to let .NET do the conversion and the second was to leverage $OFS. Here  are two ways to do it: https://blogs.msdn.microsoft.com/powershell/2006/07/15/psmdtagfaq-what-is-ofs/


# Leveraging $OFS
[char[]] $Chars =  ('w', 'o', 'r', 'd' )
$OFS = ''  # Set separator to null
[String] $String1 = $Chars
Write-Host $String1
# Or using .NET directly
[char[]] $chars =  ('w', 'o', 'r', 'd' )
$String2 = [System.String]::New($Chars)
Write-Host $string2

This is interesting, but there is a highly practical solution to an issue I’ve seen brought up in several PowerShell support places. The issue if how to construct a comma separated string of words. So if you had an array of several words such as (‘X423q420’, ‘JG75-01-27’,”PCNY”) you could easily concatenate them as follows:

$Array = (‘X423q420’, ‘JG75-01-27’,”PCNY”)
[string] $Array

Which produces:


X423q420,JG75-01-27,PCNY

You could also create the array from properties then force it to be separated by $OFS, like so:

$F = Get-ChildItem –Path X.XML
$OFS = ','
$Sring3 = [string] ($F.Fullname, ($f.length/1kb).ToString('n3'))
Write-Host $String3

Which produces this:

C:\foo\X.XML,0.317

You learn something nearly every day!




Sunday, February 18, 2018

Using Azure PowerShell and PowerShell 3 or 4? You need to update PowerShell SOON (probably).

I recently saw a GitHub Pull Request (https://github.com/Azure/azure-powershell/issues/5149) for the Azure PowerShell cmdlets (the PR was merged into Version 5.3.0 of the Azure cmdlets). Besides from the continuing improvements that each version brings, I noted one very interesting sentence: 'PowerShell version 3 and 4 will no longer be supported starting in May 2018. Please update to the latest version of PowerShell 5.1 '

What does this mean? Well – it means that after May this year, if you are running either PowerShell V3 or V4, new versions of the Azure cmdlets may not longer work – and are not supported in any case. That is not to say that either the sky is going to fall in! Older versions of the cmdlets should continue to work and most of the newer cmdlets should work too. Note the ‘should’. But why take the risk. You have several months before the lack of support begins. But you should start to plan now if you are still using PowerShell V3 or V4 to manage Azure.

So what should you do? The answer should be fairly obvious – if you are using Azure and the Azure cmdlets, just upgrade to the latest version of PowerShell (i.e. 5.1). This new version of PowerShell should work just fine on all supported versions of Windows. Of course, if you are still using XP to manage Azure then you may have some issues trying to upgrade, although an OS upgrade to Windows 10 would fix this problem.

The upgrade of PowerShell should be a no brainer. I suspect many (most?) readers here are already running later versions!  There should be no issue, but if you are using Exchange, tread carefully to ensure that the version of PowerShell you are thinking of upgrading to is going to work with and is supported by your version of Exchange.  This is probably not going to be an issue if you using hosted Exchange (O365).

It seems to me that this is the start of removing all support for PowerShell V3 and V4. V5 and V5.1 are sufficiently better to make the upgrade most welcome. Loads more cmdlets, improvements in workflows etc are all goodness that comes from the Upgrade.

What is your take?

Saturday, January 20, 2018

Power-User–a great productivity add-in for PowerPoint

I do a lot of PowerPoint presentation – I train on a variety of technical subjects and PowerPoint has been my ‘friend’ for as long as I can remember! Over the years, PowerPoint has evolved, but I still prefer the older menu structure vs the ribbon. But such is life – with the menu or ribbon, PowerPoint is an awesome product. With that said, I do find remembering where the key features are to be found.

I’ve just started using a new tool, Power-User (https://www.powerusersoftwares.com/) which is an add-in for both PowerPoint or Excel. When you open PowerPoint, once this add-in is installed, you get a new ribbon item with great tools, which looks like this:

image

Thus, you see all the useful PowerShell features all in one place. Power-User helps with creating a variety of effects including icons, diagrams, colour management etc., etc., etc. And as if that were not enough, Power-User also has some cool Excel tools as well, like this:

image

I love this tool and would not be without it!  For more details on this cool product, see the presentation video at: https://youtu.be/xtFGSnQnWpE.

Power-User is, however, a commercial product. Students and teachers can get this for free, but for commercial use individual licenses are €198/year. For larger companies, a bulk license can reduce the cost per user. So not free, but well worth the fee if you are doing a lot of PowerPoint. My only regret is that I did not find this tool years ago!