Notice: Function _load_textdomain_just_in_time was called incorrectly. Translation loading for the twentyseventeen domain was triggered too early. This is usually an indicator for some code in the plugin or theme running too early. Translations should be loaded at the init action or later. Please see Debugging in WordPress for more information. (This message was added in version 6.7.0.) in /var/www/html/wp-includes/functions.php on line 6121
Powershell – Page 3 – SCCMOG – Deployment Blog

Import IP Boundaries and Boundary Groups PowerShell SCCM ConfigMgr

This script is designed to work in harmony with the Export Sites and Subnets to CSV script I blogged about recently. The CSV file that is created by that script can then be used to import IP Subnet Boundaries and Groups with this PowerShell script.

Each Site will be Created as a Boundary Group and each Subnet listed with that Site in the CSV will be created as a IP Subnet Boundary associated to the Boundary Group.

Here is the Script:

#########################################################################################################
#Script Name:   Import Boundaries and Boundary Groups from CSV                                          #
#Script Author: SCCMOG - Richie Schuster 06/03/2017 WWW.SCCMOG.COM                                      #
#########################################################################################################
#Script Usage: ImportBoundariesandGroups.ps1 -CSVParam MyCSV.csv                                  #
#########################################################################################################

#CSV Name accepted as first PARAM
Param
(
[parameter(mandatory=$true,HelpMessage="Please, provide your SiteCode.")][ValidateNotNullOrEmpty()][String]$SiteCode,
[parameter(mandatory=$true,HelpMessage="Please, provide a CSV to import. It must be in the same folder as the script e.g. Sites.CSV")][ValidateNotNullOrEmpty()][String]$CSVParam
)

# Check for elevation
Write-Host "Checking for elevation"
If (-NOT ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole(`
    [Security.Principal.WindowsBuiltInRole] "Administrator"))
{
    Write-Warning "Oupps, you need to run this script from an elevated PowerShell prompt!`nPlease start the PowerShell prompt as an Administrator and re-run the script."
    Write-Warning "Aborting script..."
    Break
}

If ($CSVParam -ne ""){

    #Import CSV
    $path     = Split-Path -parent $MyInvocation.MyCommand.Definition 
    $newpath  = $path + "\$CSVParam"
    #Check location of CSV is valid.
    If (Test-Path $newpath){
    $BoundaryList = Import-Csv -Path $newpath
    #Import ConfigMgr Module
    Import-Module "$($ENV:SMS_ADMIN_UI_PATH)\..\ConfigurationManager.psd1"
    #Set the current location to be the site code.
    Set-Location "$SiteCode`:"

        foreach ($_ in $BoundaryList){
            #Check If Boundary Group Already Created
            $getbg = Get-CMBoundaryGroup -Name $($_.Name)
 
            #If no bounday group maching that name create it
            if ($getbg -eq $null){
                New-CMBoundaryGroup -Description $($_.Name) -Name $($_.Name)
                }

            #Split on /
            $Subnet,$Bit = $_.Subnet.split('/',2)

            #Check if Boundary is already Created
            $getbn = Get-CMBoundary | where Value -eq $Subnet
    
            #If it is not then create new boundry and add it to Boundary Group
            if ($getbn -eq $null){
            New-CMBoundary -DisplayName $($_.Name) -BoundaryType IPSubnet -Value $Subnet
            Add-CMBoundaryToGroup -BoundaryGroupName $($_.Name) -BoundaryName $($_.Name)
                }
            }
        }
    Else{
    Write-Host "Please enter VALID CSV Name. Make sure it is in the same folder as this script." -ForegroundColor Cyan
    }
}
Else{
    Write-Host "Please enter CSV Name. Make sure it is in the same folder as this script." -ForegroundColor Cyan
}
###############################################################################################################

Below is a demonstration of the Script complete:

Import Boundaries and Groups PowerShell Script output
Import Boundaries and Groups PowerShell Script output
IP Subnet Boundaries Created
IP Subnet Boundaries Created
Boundary Groups Created
Boundary Groups Created
CSV from Export Script
CSV from Export Script

Export Sites and Subnets PowerShell to CSV

I came across an issue the other day when setting up a primary site for a customers Regional Office. The issue was that when enabling discovery methods namely the “Active Directory Forest Discovery“. As I’m sure you are aware there is a useful tick box that can be marked to “Automatically create IP address range boundaries for IP subnets when they are discovered“. This although a usually a useful check box caused the Discovery Method to pull back EVERY subnet listed globally… about 2500)!

So to get round this I created this PowerShell Script to export the Sites required and the Subnets associated with the sites in Active Directory Sites and Subnets. This script will export the data to a CSV that can then be imported into ConfigMgr later using this script.

Note: If you run the script without Parameters and just want to enter one Site to export, just hit enter on the next line and it will then ask you for save location.

Note: As in the image at the bottom of this page the save location must include the CSV Name e.g. “C:\temp\sites.csv”

#################################################################################################################################
#Script Name:   Export Specific Sites and Subnets to CSV                                                                        #
#Script Author: SCCMOG - Richie Schuster 06/03/2017 WWW.SCCMOG.COM                                                              #
#################################################################################################################################
#Script Usage: ExportSitesandSubnets -siteNames "Jersey" for single site , seperated "Jersey,Guernsey" -CSVOut C:\temp\site.csv #
#              for multiple.                                                                                                    #
#################################################################################################################################

#Params
Param
(
[parameter(mandatory=$true,HelpMessage="Please, provide Site Name(s). To list more than one site seprate with , e.g. Jersey,Guernsey ")][ValidateNotNullOrEmpty()][String[]]$siteNames,
[parameter(mandatory=$true,HelpMessage="Please, provide a location to save the Exported CSV with the filename. e.g C:\Temp\SCCMOGSites.CSV")][ValidateNotNullOrEmpty()][String]$CSVOut
)

 
#If entery is input run script
If ($siteNames -ne $null){

#Set Lists
[System.Collections.ArrayList]$sites = @()
[System.Collections.ArrayList]$sitesubnets = @()

#Get each site list in sitenames variable and add to variable
for ($i=0; $i -lt $siteNames.Count; $i++){
    $sites += [System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().Sites | Where-Object -Property Name -like $siteNames[$i]
    }

#Loop through each site and create simple match 
foreach ($site in $sites){
	foreach ($subnet in $site.subnets){
	   $temp = New-Object PSCustomObject -Property @{
	   'Name' = $site.Name
	   'Subnet' = $subnet; }
	    $sitesubnets += $temp
	}
}
#Export to CSV
$sitesubnets | Export-Csv $CSVOut -Force
}
#If params are not specified then inform.
Else{
    Write-host 'Script Param must be used : "ExportSitesandSubnets -siteNames Jersey" for single site or , seperated "Jersey,Guernsey" for multiple followed by -CSVOut C:\temp\site.csv' -ForegroundColor Yellow
    }
#########################################################################################################

The Image below shows the script being run and the output:

Export Sites and Subnets to CSV PowerShell Script
Export Sites and Subnets to CSV PowerShell Script

Set Site Proxy Account and Address SCCM PowerShell

I was at a clients the other day and wanted to update the proxy account information for the Primary Site Server so thought I would script it quickly. This Script will create an account in ConfigMgr and then associate that with the Proxy details specified to the Site System. It must be run with access to the ConfigMgr Module for PowerShell and administrative rights.
Here it is:

#########################################################################################################################
#Author:       SCCMOG - Richie Schuster - SCCMOG.COM                                                                    #
#Date:         02/05/2017                                                                                               #
#Name:         Set-CMProxyAccount.ps1                                                                                   #
#RunAs CMD:    Powershell.exe -Executionpolicy Bypass -File Set-CMProxyAccount.ps1 -Account SCCMOG\Admin                #
#              -Password CantCrackMe -SSFQDN CM-01.SCCMOG.COM -SiteCode SOG -ProxSName proxy.sccmog.com -ProxySPort 8080#
#              Just running the script will prompt for all parameters.                                                  #
#Description:  This script will add a new account to the site and then associate it with the proxy account for the site #
#              system.                                                                                                  #
#########################################################################################################################


Param
(
[parameter(mandatory=$true,HelpMessage="Please, provide a account name. Domain\Account or Account")][ValidateNotNullOrEmpty()]$Account,
[parameter(mandatory=$true,HelpMessage="Please, provide the password to be used.")][ValidateNotNullOrEmpty()]$Password,
[parameter(mandatory=$true,HelpMessage="Please, provide the Site Server FQDN.")][ValidateNotNullOrEmpty()]$SSFQDN,
[parameter(mandatory=$true,HelpMessage="Please, provide the Code.")][ValidateNotNullOrEmpty()]$SiteCode,
[parameter(mandatory=$true,HelpMessage="Please, provide Proxy Server Name.")][ValidateNotNullOrEmpty()]$ProxySName,
[parameter(mandatory=$true,HelpMessage="Please, provide Proxy Server Port.")][ValidateNotNullOrEmpty()]$ProxySPort
)

# Check for elevation
Write-Host "Checking for elevation"
If (-NOT ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole(`
    [Security.Principal.WindowsBuiltInRole] "Administrator"))
{
    Write-Warning "Oupps, you need to run this script from an elevated PowerShell prompt!`nPlease start the PowerShell prompt as an Administrator and re-run the script."
    Write-Warning "Aborting script..."
    Break
}

# Import the ConfigurationManager.psd1 module 
Write-Host "Importing ConfigMgr Module..." -ForegroundColor Yellow
Import-Module "$($ENV:SMS_ADMIN_UI_PATH)\..\ConfigurationManager.psd1"
# Set the current location to be the site code.
Write-Host "Setting Location to ConfigMgr Drive..." -ForegroundColor Yellow
Set-Location "$SiteCode`:"


#Store the pass as a secure string
Write-Host "Storing Password securely...." -ForegroundColor Yellow
$Secure = ConvertTo-SecureString -String $Password -AsPlainText -Force
#Create Account
Write-Host "Creating New Account $Account...." -ForegroundColor Yellow
New-CMAccount -UserName $Account -Password $Secure -SiteCode $SiteCode

#Set Site Server Proxy
Write-Host "Setting Proxy information...." -ForegroundColor Yellow
Set-CMSiteSystemServer -SiteSystemServerName $SSFQDN -SiteCode $SiteCode -EnableProxy $True -ProxyServerName $ProxySName`
                       -ProxyServerPort $ProxySPort -ProxyAccessAccount (Get-CMAccount $Account) -PassThru

########################################################################################################################


Demonstration of running the script:

Example of running the script in PowerShell.

Site System Properties after running Script:

Site System Properties after running the Script.

Account Properties:

Account Properties

 

SCCM Auto Snapshot a VM before Patching Task Sequence – PowerCLI

A while ago I mentioned in a post about creating a bespoke patching task sequence for a client who wanted to snap shot every VM before patching. To do this I created a silent install wrapper for PowerCLI using PowerShell.

Anyway, as per the request… here is the script I used to snapshot a VM before patching it during the Task sequence. It must be run as a command line step and using an account that has access to VSphere.
 

########################################################################################################################
#Author:       SCCMOG - Richie Schuster - SCCMOG.COM                                                                   #
#Date:         05/01/2017                                                                                              #
#Name:         Auto Snapshot VM before Patching                                                                        #
#RunAs CMD:    Powershell.exe -Executionpolicy Bypass -File PrePatchSnapShot.ps1                                       #
#Description:  This script has been created to auto snapshot a VM before patching by a task sequence from SCCM.        #
#              The script must be run as a Command Line in the task sequence by an account with access to VSphere.     #
########################################################################################################################

#Variables
$VMname = "$env:COMPUTERNAME.YOURDOMAIN.COM"
$VIserver = "YOURVISERVER.YOURDOMAIN.COM"
#$Username = "YourDomain\admin-SCCMOG"
#$Password = "CrazyPass"

#Create Credential to pass securely
#$Cred = New-Object System.Management.Automation.PSCredential($Username, (ConvertTo-SecureString $Password -AsPlainText -Force))

#Add the VMware snapin if not added
If ((Get-PSSnapin -Name VMware.VimAutomation.Core -ErrorAction SilentlyContinue) -eq $null ) {
    Add-PSSnapin VMware.VimAutomation.Core
    }

#Connect to VIC001
If ($global:DefaultVIServer -eq $null ) {
    Connect-VIServer -Server $VIserver #-Credential $Cred -Verbose
    }
ElseIF ($global:DefaultVIServer -ne $VIserver ) {
    #Disconnect all server connections
    Disconnect-VIServer -Server $global:DefaultVIServers -Force -Confirm:$false -WarningAction SilentlyContinue -ErrorAction SilentlyContinue | Out-Null
    #Re-connect to specific server
    Connect-VIServer -Server $VIserver
    }

#Reset Connected Variable
$Connected = $global:DefaultVIServer.Name -eq $VIserver

If ($Connected -eq $true) {

    #Snapshot Time
    #Time Date for Snapshot name
    $Date = Get-Date
    $DateShort = $Date.ToShortDateString() -replace '[/]'
    $TimeShort = $Date.ToShortTimeString()
    $Snapshotname = "Before Patching $TimeShort $DateShort"

    #Take Snapshot
    New-Snapshot -VM $VMname -Name $Snapshotname -Description "This Snapshot was taken before patching the VM from the SCCM TaskSequence. $Date" -Verbose

    #Check Snapshot complete
    $SnapShots = Get-Snapshot -VM $VMname
    $Taken = $Snapshots.Name.Contains($Snapshotname)
    
    #If found Disconnect and Exit Script Success 0
    If ($Taken -eq $true) {
        Disconnect-VIServer -Server $VIserver -Force -Confirm:$false -WarningAction SilentlyContinue -ErrorAction SilentlyContinue | Out-Null
        Exit 0
        }
    #If Failed Exit Script 999 Failing the Tasksequence
    Else {
    Exit 999
    }
}

Elseif ($Connected -eq $false) {
    Exit 911
    }
Else {
    Exit 912
    }
    
###################################################################################################################### 

Copyright 2016 SCCMOG | All Rights Reserved