Mar 102015
 

One of my latest projects at work was to write a powershell script to remove arbitrarily selected registry entries. Here are some tips for getting along with remove-itemproperty and the registry so that it works the first time. As always, if you have any corrections or something else I could try, let me know. I could have used the reg command but that’d be cheating. ūüėČ

So let’s define a registry path. This should be enough to work with Remove-Itemproperty becuase it does accept paths.

$RegPath1 = 'HKLM:\SOFTWARE\Wow6432Node\Cisco Systems, Inc.\Communicator'

Unfortunately it isn’t. If we run the following:

Remove-ItemProperty -Path $RegPath1 -Name TftpServer1 -Force

Powershell gives us this nice error. Which is fun because in CM12 we are running as “nt authority\system,” the grand kahuna of all accounts. More godly than administrator.

ERROR: Remove-ItemProperty : Requested registry access is not allowed.
CiscoIPC_Regkey_Removal.ps1 (24): ERROR: At Line: 24 char: 12
ERROR: + $RegKey1 | Remove-ItemProperty -Name TftpServer1 -Force
ERROR: + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
ERROR: + CategoryInfo : PermissionDenied: (HKEY_LOCAL_MACH...c.\Communicator:String) [Remove-ItemProperty], SecurityException
ERROR: + FullyQualifiedErrorId : System.Security.SecurityException,Microsoft.PowerShell.Commands.RemoveItemPropertyCommand

There is another way to do this. Instead of giving Remove-ItemProperty the path, use it in conjunction with Get-ItemProperty. The following works.

$RegPath1 = 'HKLM:\SOFTWARE\Wow6432Node\Cisco Systems, Inc.\Communicator'

$RegKey1 = Get-ItemProperty $RegPath1

$RegKey1 | Remove-ItemProperty -Name TftpServer1 -Force

In this case were getting an the registry key as an object and passing it to Remove-ItemProperty, which works.

Now for detecting that the key is gone. One of the other issues I encountered is that if you’re going to use if() to see if the value still exists, you need two conditions.

  • The first condition is that value¬†has a value or …
  • The second condition is that the value¬†is equal to $null.

I ran into this existential dilemma whenever I used the first condition only is that the if() would fail if the key value was there but didn’t have any actual value to it, which happens. So we add an -or and check to see if it -eq $null. Like so:

if (($RegKey1.TftpServer1) -or ($RegKey1.TftpServer1 -eq $null)) {
$Checksum++
}

And the $Checksum will be incremented if the value exists as either null or has a value. I’ll leave the significance of the checksum up to you.

As a side note: I really wish compliance settings in SCCM 2012 could allow for direct remediation (removal) of registry keys if they shouldn’t exist, but unfortunately that isn’t the case.

Dec 222014
 

This is an experimental PowerShell script that looks at all the physical network adapters on a machine and verifies that they are at or above an arbitrary link speed set in the script. It works by querying the MSNdis_LinkSpeed class in WMI, filtering out non-physical adapters, and then checking each one to make sure the link speed is above the $MinSpeed value that you set. It then returns TRUE or FALSE.

I believe it is useful to use a greator than or equal to comparison instead of saying that all links must equal the minimum speed, especially in server environments where you may have a mixed environment of some servers with gigabit links for instance, and then another set of servers or virtual machines with 10gig links.

I don’t see this being useful in a PC environment because you have less control over what a desktop is hooked in to at any given point in time. Though it may still be useful if you want to enforce such a policy, like trading floor must be at gigabit or higher, and you want to catch non-compliance.

Obviously I can’t account for every InstanceName that isn’t a physical adapter. If there is a better way, by all means let me know and I’ll modify the script, but here it is!

# Robert's experimental NIC speed compliance script. 
# Emphasis on EXPERIMENTAL. 
# It will not break anything but it may not give back a sane result. 
# Manually check suspect compliance, bad compliance will probably come
# from non-physical nics where I didn't account for the InstanceName
# below when it came from MSNdis_LinkSpeed. 

# Minimum allowed speed in megabits. 
$MinSpeed = '1000' 

# This is used for compliancy.
$NonCompliant = 0

# Get link speed for all physical network adapters. 
$nics = Get-WmiObject -Namespace root\wmi -Class MSNdis_LinkSpeed | where {`
$_.InstanceName -notlike '*miniport*' -and `
$_.InstanceName -notlike '*WAN*' -and `
$_.InstanceName -notlike '*1394*' -and `
$_.InstanceName -notlike '*ISATAP*' -and `
$_.InstanceName -notlike '*Bluetooth*' -and `
$_.InstanceName -notlike '*RAS*' -and `
$_.InstanceName -notlike 'Direct Parallel' -and `
$_.InstanceName -notlike '*tunnel*' -and `
$_.InstanceName -notlike '*6to4*' -and `
$_.InstanceName -notlike '*Deterministic*' -and `
$_.InstanceName -notlike '*miniport*' -and `
$_.InstanceName -notlike '*kernel*'
}

# Go through list of NICS and make sure speed is above $MinSpeed
foreach ($nic in $nics) {
    
    #Make the link speed in megabits instead of bits.
    $LinkSpeed = $nic.NdisLinkSpeed/10000

    #See if this NIC is compliant.
    if ($LinkSpeed -lt $MinSpeed) {
        $NonCompliant++
    }
}

# Am I compliant?
if ($NonCompliant -eq 0) {
    write-host TRUE
    } else {
    write-host FALSE
}
Nov 232014
 

The following detection script accomplishes the following.

  • Determines if virtual memory is automatically managed. The desired configuration according to the script is that the pagefile should be managed manually (true can be changed to false if you want to go the automagic route).
  • If the pagefile is not automatically managed, the script determines if the size of the page file is at least double the amount of visible physical memory.

I’m working on a remediation script, but for now I figure’d I would share the love.

# This script simply checks to see if Windows is handling the page file
# automagically. Then if no, it verifies to make sure that the swap file
# is set at or over twice the available memory. 

$system = get-wmiobject -Class win32_ComputerSystem

if ($system.AutomaticManagedPagefile -eq $true) {
    write-host FALSE
    } else {  

    $mem = get-wmiobject -Class win32_OperatingSystem | select-object TotalVisibleMemorySize,TotalVirtualMemorySize

    [int64]$vismem = $mem.TotalVisibleMemorySize
    [int64]$vrtmem = $mem.TotalVirtualMemorySize

    if ($vrtmem -ge ($vismem * 2)) {
        write-host TRUE
        } else {
        write-host FALSE
    }
}

 

Nov 112014
 

Here is a way for you to keep your EMIE site list up to date using CI. Enterprise Mode IE is Microsoft’s method for allowing backwards compatibility with sites that do not fully support Internet Explorer 11’s Edge mode. I don’t go into detail about how to set up EMIE, more information on how to set it up can be found via MSDN.

First we start with the detection script. This script returns the version number of your site list XML. Be sure to replace the $file string listed with the correct path and file name of your EMIE list XML.

 
# EMIE XML Version Check (Detection) Script for CM12 Compliance Settings
# by Robert Hollingshead

# November 11th, 2014
# Find more CM12 Compliance Setting scripts at occurative.com!

# Supress error messages.
$ErrorActionPreference = "SilentlyContinue"

# Enter the path and name of the XML file here. 
$file = '{enter path and filename here}'

# Get the XML Content and then unwrap its tags into individual lines.
# We could leave out the split method and just go by the entire InnerXml,
# but IMHO, this way makes more sense and is friendly to ANY 
# odd modifications of the remediation script should they be needed. 

Try {
    [xml]$sites = Get-Content $file
    $unwrappedsites = $sites.innerxml.split('</>')

    # Look for the rules version, split out the line, 
    # and output the second string which will be the
    # version itself. 

    ForEach($line in $unwrappedsites) {
        if ($line -like "*rules version*") {
            write-host $line.split('"')[1]
            break
        }
    }

    # If the split of $sites failed, we'll catch it and
    # spit out versin 0 to indicate the file doesn't exist.

    } catch {   
    write-host 0
}

The detection script is going to return the current version of the XML file on the client, not a true or false. So your compliance rule will be equal to the version you want all your clients to be at. How to get that updates can be done via this remediation script. First thing, there are two values that must be changed, the $version, and the $file strings. $version will be the equal to the version you want all your clients to be at. Make sure¬† you have it set to the same version as in your compliance rule or you’ll never be compliant. The second is the $file string, which will be the same as in the detection script.

Next¬† you will add all the domains. There are four lines beginning with “$domain = New-Object PSOBject.” We are building an array of Domains as well as if they are to be excluded or included in EMIE. Each domain will be a TLD. True means “exclude this site from EMIE” and is useful for preventing an intranet site from running in compatibility mode. False means “include this site in EMIE” and is useful for placing a site on the internet in compatibility mode, or if the site is setting its compatibility via META tag and you wish to override. Here is the script, stay tuned after the script for a few notes.

# EMIE XML Update (Remediation) Script for CM12 Compliance Settings
# by Robert Hollingshead

# November 11th, 2014
# Find more CM12 Compliance Setting scripts at occurative.com!

# This script keeps your EMIE (Enterprise Mode IE 11) XML up to date.

# Enter the resultant version here. This is your XML list version.
# Increment when there are changes. 
# Make sure that you change the compliance rule to match. 
$version = "{enter version number here}"

# Enter the path and name of the XML file here. 
$file = '{enter path and filename here}'

# Setup Array for domains and the resulting xml 

[system.array]$domains = $null
[system.array]$sitesxml = $null

#Add domain here.
#False indicates that EMIE should run for non-intranet site. 
#False also indicates that EMIE should run for intranet sites that are saying they are
#compatible via server meta tag.
#True indicates that EMIE should not run for intranet site. 
# Copy the following four lines for each new domain. Don't forget to increment the version
# if you make any changes. 
$domain = New-Object PSObject
$domain | Add-Member -membertype noteproperty -Name Domain -Value "{tld like microsoft.com}"
$domain | Add-Member -membertype noteproperty -Name Exclude -Value "{false or true}"
$domains = $domains + $domain


#Now let's write out the XML. We build an array that will be written out to file. 

# Compile the version line and the opening EMIE tag.
$line = New-Object PSObject
$line = ''
$sitesxml = $line
$line = '  '
$sitesxml = $sitesxml + $line

# Compile the domain tags.
ForEach ($domain in $domains) {
    $line = '    ' + $domain.Domain + ''
    $sitesxml = $sitesxml + $line
}

# Compile the closing tags.
$line = '  '
$sitesxml = $sitesxml + $line
$line = ''
$sitesxml = $sitesxml + $line

# Output to the file. 
$sitesxml | out-file $file

write-host TRUE

Obviously there is some room for improvement in this script. While I can include TLD’s right now, I cannot include subdomains just yet, that ability will be forthcoming in another update of this script, or if you wish to update it yourself and contribute back that is fine too.

Enjoy!

Nov 052014
 

EDIT 11/10/14: I found and corrected a bug in the detection script. There is a chance in certain configurations that the detection script might miss cards. I modified it so that wouldn’t happen.

The following detection and remediation scripts are designed to be placed into as compliance settings in a configuration item in CM12. They are heavily modified from an original powershell function published on the TechNet gallery. Where the original powershell script is a run-once affair, these two scripts will enable you to establish compliance on all desktops, laptops, and especially servers where it is generally not a good idea to power manage your NICs.

I recommend testing before deployment. Note that the remediation script will run and the detection script will show compliance, but where the original script could force a reboot, the remediation script here does no such thing. This is intentional as I believe it would be better in practice to let the compliant machines reboot through other means, such as during a patch cycle or when the end user shuts down for the evening.

The detection script (copy and paste, the lines will remain intact):

# NIC Power Management Detection Script for CM12 Compliance Settings

# Based off of the script found at https://gallery.technet.microsoft.com/scriptcenter/Disable-turn-off-this-f74e9e4a
# Modified by Robert Hollingshead
# November 10th, 2014
# Find more CM12 Compliance Setting scripts at occurative.com!

# This script detects power management status for all physical NICs.

#Original scripts comments:
#find only physical network,if value of properties of adaptersConfigManagerErrorCode is 0,  it means device is working properly. 
#even covers enabled or disconnected devices.
#if the value of properties of configManagerErrorCode is 22, it means the adapter was disabled. 

# This is to calculate compliance. If both of these are equal at the end then all NICs are compliant.
$SettingChecksum = 0
$NICCount = 0

$PhysicalAdapters = Get-WmiObject -Class Win32_NetworkAdapter|Where-Object{$_.PNPDeviceID -notlike "ROOT\*" `
	-and $_.Manufacturer -ne "Microsoft" -and $_.ConfigManagerErrorCode -eq 0 -and $_.ConfigManagerErrorCode -ne 22} 
	
Foreach($PhysicalAdapter in $PhysicalAdapters) {
	$PhysicalAdapterName = $PhysicalAdapter.Name
	
    #check the unique device id number of network adapter in the currently environment.
	$DeviceID = $PhysicalAdapter.DeviceID
	If([Int32]$DeviceID -lt 10) {
		$AdapterDeviceNumber = "000"+$DeviceID
		} Else {
		$AdapterDeviceNumber = "00"+$DeviceID
	}

	#check whether the registry path exists.
	$KeyPath = "HKLM:\SYSTEM\CurrentControlSet\Control\Class\{4D36E972-E325-11CE-BFC1-08002bE10318}\$AdapterDeviceNumber"
	
    If(Test-Path -Path $KeyPath) {
		$PnPCapabilitiesValue = (Get-ItemProperty -Path $KeyPath).PnPCapabilities
		If($PnPCapabilitiesValue -eq 0){
			#This adapter isn't compliant!
            $SettingChecksum++		
		}
		If($PnPCapabilitiesValue -eq $null) {
            #This adapter isn't compliant!
		    $SettingChecksum++				
		}
    }			
}


# Are we compliant?
If ($SettingChecksum -eq 0) {
    write-host TRUE
    } else {
    write-host FALSE
}

The remediation script (copy and paste, the lines will remain intact):

# NIC Power Management Remediation Script for CM12 Compliance Settings

# Based off of the script found at https://gallery.technet.microsoft.com/scriptcenter/Disable-turn-off-this-f74e9e4a
# Modified by Robert Hollingshead
# November 5h, 2014
# Find more CM12 Compliance Setting scripts at occurative.com!

# This script turns off power management for all physical NICs.

#Original scripts comments:
#find only physical network,if value of properties of adaptersConfigManagerErrorCode is 0,  it means device is working properly. 
#even covers enabled or disconnected devices.
#if the value of properties of configManagerErrorCode is 22, it means the adapter was disabled. 

$PhysicalAdapters = Get-WmiObject -Class Win32_NetworkAdapter|Where-Object{$_.PNPDeviceID -notlike "ROOT\*" `
-and $_.Manufacturer -ne "Microsoft" -and $_.ConfigManagerErrorCode -eq 0 -and $_.ConfigManagerErrorCode -ne 22} 
	
Foreach($PhysicalAdapter in $PhysicalAdapters) {
    
    $InterfaceChecksum++
	$PhysicalAdapterName = $PhysicalAdapter.Name
		
    # Check the NIC ID Number.
	
    $DeviceID = $PhysicalAdapter.DeviceID
	
	If([Int32]$DeviceID -lt 10) {
		$AdapterDeviceNumber = "000"+$DeviceID
	} Else {
		$AdapterDeviceNumber = "00"+$DeviceID
	}
		
	# See if the registry path exists.
	$KeyPath = "HKLM:\SYSTEM\CurrentControlSet\Control\Class\{4D36E972-E325-11CE-BFC1-08002bE10318}\$AdapterDeviceNumber"
		
    If(Test-Path -Path $KeyPath) {
		$PnPCapabilitiesValue = (Get-ItemProperty -Path $KeyPath).PnPCapabilities
		If($PnPCapabilitiesValue -eq 0){
			#setting the value of properties of PnPCapabilites to 24, it will disable save power option.
			Set-ItemProperty -Path $KeyPath -Name "PnPCapabilities" -Value 24 | Out-Null			
		}
		If($PnPCapabilitiesValue -eq $null) {
                #setting the value of properties of PnPCapabilites to 24, it will disable save power option.
				New-ItemProperty -Path $KeyPath -Name "PnPCapabilities" -Value 24 -PropertyType DWord | Out-Null				
		}
	}		
}

write-host TRUE

 

I am always open to improvements to these scripts. If you find something that could use improvement just let me know via the comments below!

Jan 152014
 

If you’re working with SCCM 2012 Desired Configuration Management and want to create a CI for local machine certificates, here’s part 1 of a 2 part equation that is evolving. The remediation script is still in the works, but for right now, here’s a script that does the following.

  1. Query the Local Machine for a list of certs assigned to it.
  2. Check the list of certs for a valid machine certificate.
  3. Verify that the certificate has not expired.
  4. Verify that the certificate has the proper template (that you specify).
  5. And finally, verify that the certificate has the proper subject (again, that you specify).
  6. If items 3, 4, and 5 are all in agreement, echo “True” back to SCCM, or “False” if no machine certs are valid.

Note that there are a few strings you need to specify. $template and $subject need to be set or this isn’t going to work. You can also set $hostname to your hearts content. There’s obviously a lot of different ways you can modify this script, but for creating a CI in SCCM 2012 DCM this is a good start. Have fun!

 
########################################################
### Check for existence of valid machine certificate ###
########################################################
#
# By Robert Hollingshead
# Contributions by Steven Buck
#
# Transform function for Template property from
# http://social.technet.microsoft.com/Forums/windowsserver/en-US/187698d0-5602-4301-9d0c-85e89d948ea2/user-powershell-to-get-the-template-used-to-create-a-certificate?forum=winserversecurity
#
#
# Checks the certificate store for a valid machine
# certificate then outputs True.
#
########################################################

# Function to get Template.
function Transform-Certificate {
[CmdletBinding()]
    param(
 [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
 [Security.Cryptography.X509Certificates.X509Certificate2]$cert
 )
    process {
        $temp = $cert.Extensions | ?{$_.Oid.Value -eq "1.3.6.1.4.1.311.20.2"}
 if (!$temp) {
            $temp = $cert.Extensions | ?{$_.Oid.Value -eq "1.3.6.1.4.1.311.21.7"}
 }
        $cert | Add-Member -Name Template -MemberType NoteProperty -Value $temp.Format(1) -PassThru
 }
}

# Assume the store doesn't contain a valid cert.
[bool]$ValidCert = $false # Assume false.

# Get hostname+fqdn
$hostname = [system.net.dns]::gethostbyname(($env:computername)).Hostname

# Put the template string to match here. * is wildcard
$template = "*{a chunk of your template name to verify}*"

# Put the subject string to match here.
$subject = "CN=$hostname"

# Analyze each certificate in Local Machine.
foreach ($Certificate in (get-childitem -Path Cert:\LocalMachine\My | Transform-Certificate))
{
    If ($Certificate.Subject -eq $subject)  # If certificate has a proper subject.
    {
        If ($Certificate.NotBefore -le (Get-Date)) # If certificate has not expired.
        {
            If ($Certificate.Template -like $template) # If cert has proper template.
            {
                $ValidCert = $true # It's true!
            }
        }
    }
}

If ($ValidCert -eq $true)
    {
        write-host "True"
    }
else
    {
        write-host "False"
    }
Dec 122013
 

Here’s a helpful tip, see here for more details.

I was working on a script to remove specific Modern packages from Windows 8.1 and I needed¬†a quick way to see what was installed. “get-appxprovisionedpackage -online” yielded the following useless results.

PS C:\windows\system32> get-appxprovisionedpackage -online

DisplayName  : Microsoft.BingFinance 
Version      : 2013.809.632.3676 
Architecture : neutral 
ResourceId   : ~ 
PackageName  : Microsoft.BingFinance_2013.809.632.3676_neutral_~_8wekyb3d8bbwe

DisplayName  : Microsoft.BingFoodAndDrink 
Version      : 2013.820.258.2561 
Architecture : neutral 
ResourceId   : ~ 
PackageName  : Microsoft.BingFoodAndDrink_2013.820.258.2561_neutral_~_8wekyb3d8bbwe

The list is longer, but you get the idea. Anyway it’s completely useless to me. The solution is to use select-object to pick out the PackageName value from the collection of objects. Simple really, just use a pipe along with the “select-object” cmdlet then specify the name of the value you want.:

PS C:\windows\system32> get-appxprovisionedpackage -online | select-object PackageName

PackageName
-----------
Microsoft.BingFinance_2013.809.632.3676_neutral_~_8wekyb3d8bbwe
Microsoft.BingFoodAndDrink_2013.820.258.2561_neutral_~_8wekyb3d8bbwe
Microsoft.BingHealthAndFitness_2013.813.243.3760_neutral_~_8wekyb3d8bbwe
Microsoft.BingMaps_2013.809.2206.5385_neutral_~_8wekyb3d8bbwe
Microsoft.BingNews_2013.809.636.2800_neutral_~_8wekyb3d8bbwe
Microsoft.BingSports_2013.809.637.2803_neutral_~_8wekyb3d8bbwe
Microsoft.BingTravel_2013.809.639.25_neutral_~_8wekyb3d8bbwe

Ahh. Much better. Now I could take that output and figure out which Modern apps to delete. I will probably start with Bing.