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
Deployment – Page 3 – SCCMOG – Deployment Blog

PowerShell Add Variables to Machines from CSV SCCM ConfigMgr

So it used to be a bit trickier to add a custom variable or multiple variables to a machine object in SCCM/ConfigMgr. But since the addition of the awesome New-CMDeviceVariable Cmdlet it’s a breeze!

Basically I’m in the midst of automating a clients Server Builds. As they have a lovely spreadsheet with all details of each server I thought I’d nock this up as a starter this evening.

So the script imports the CSV specified and from there creates the variables supplied in the CSV to the machine that is named in the CSV (that’s a lot of CSV). If the script cant find the Machine object (say you are doing hundreds or thousands!) that is named in the CSV file it will log that name to a text file called “NotFound.txt” in the script root folder.

As always comments throughout the script explain every step.

Anyway here is the script and CSV example:

#########################################################################################################
#Script Author: SCCMOG - Richie Schuster 24/05/2017 WWW.SCCMOG.COM                                      #
#Modded By:     Your Name Here                                                                          #
#Script Name:   Add Variables to Machines from CSV                                                      #
#########################################################################################################
#Script Usage: Add-VariablesMachines.ps1 -SiteCode S0G -CSVParam MyCSV.csv                              #
#########################################################################################################

#Script Parameters
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. YourCSV.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 "Please run from elevated PowerShell prompt!"
    Write-Warning "Aborting script..."
    Break
}

#Double check CSV param
If ($CSVParam -ne ""){

    #Create path to CSV (back compat PS 2.0)
    $path     = Split-Path -parent $MyInvocation.MyCommand.Definition 
    $newpath  = $path + "\$CSVParam"
    #Check location of CSV is valid.
    If (Test-Path $newpath){
        $MachineCSV = 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`:"
            #Loop through each machine in CSV
            foreach ($Machine in $MachineCSV){
                #Check If Machine exists
                $Exists = Get-CMDevice -Name $($Machine.Name)
                #If no machine found log to txt file and report
                if ($Exists -eq $null){
                    Write-Warning "$($Machine.Name) not Found Logged to Notfound.txt"
                    Add-Content "$path\NotFound.txt" "$($Machine.Name)" -Force
                    }
                #If machine is found Create the Variables
                Else {
                    New-CMDeviceVariable -DeviceName $($Machine.Name) -VariableName "IPAddress" -VariableValue $($Machine.IPAddress) -IsMask 0
                    New-CMDeviceVariable -DeviceName $($Machine.Name) -VariableName "SubMask" -VariableValue $($Machine.SubMask) -IsMask 0
                    New-CMDeviceVariable -DeviceName $($Machine.Name) -VariableName "Gateway" -VariableValue $($Machine.Gateway) -IsMask 0
                    New-CMDeviceVariable -DeviceName $($Machine.Name) -VariableName "DNS1" -VariableValue $($Machine.DNS1) -IsMask 0
                    New-CMDeviceVariable -DeviceName $($Machine.Name) -VariableName "DNS2" -VariableValue $($Machine.DNS2) -IsMask 0
                }
            }
        #Set location back to script root
        Set-Location $path
        }
    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
}
###############################################################################################################

CSV:

Name,IPAddress,SubMask,GateWay,DNS1,DNS2
Proliant,192.168.1.88,255.255.255.0,192.168.8.254,192.168.1.1,192.168.1.2
SCCMOG-CM-01,192.168.1.90,255.255.255.0,192.168.8.254,192.168.1.1,192.168.1.2
NotHere,192.168.1.89,255.255.255.0,192.168.8.254,192.168.1.1,192.168.1.2
NotHere2,192.168.1.89,255.255.255.0,192.168.8.254,192.168.1.1,192.168.1.2
NotHere3,192.168.1.89,255.255.255.0,192.168.8.254,192.168.1.1,192.168.1.2

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
    }
    
###################################################################################################################### 

Get Logged On User WMI PowerShell

Ever needed to figure out who is logged on when deploying software to a machine with SCCM?
Maybe you needed to do so… like me… to copy a specific file into that users AppData?

Anyway quick PowerShell script to figure out the currently logged on user of a Machine.

################################################################################
#Author: SCCMOG.COM - Richie Schuster                                          #
#Date: 04/03/2017                                                              #
#Script Name: Get Logged on User                                               #
################################################################################

#Get logged on User
$Loggedon = Get-WmiObject -ComputerName $env:COMPUTERNAME -Class Win32_Computersystem | Select-Object UserName
#Split User and Domain
$Domain,$User = $Loggedon.Username.split('\',2)
Write-Host $Domain
Write-Host $User

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

SCCM PowerCLI Silent deployment script

A couple of months ago I was asked by a client to create a method of patching to automatically snap shot a VM before applying the monthly patches with SCCM.

This as I’m sure your thinking has to be done by Task Sequence with the use of SCCM. If you not then that is how I would suggest you do it. The issue was PowerCLI and how to deploy that silently to all servers to allow for the Task Sequence to harness the PowerShell commands locally on the box without using remote PowerShell. I came across a great blog here discussing the silent install and then decided to write a PowerShell wrapper to deploy the software silently and with the use of SCCM.

The following script can be run as an Application or Package that is purely up to you. There are 2 modes, Install and Uninstall. Add these deployment command lines to your application or program to silently install PowerCLI or just run them locally:

[code language=”text”]
Powershell.exe -Executionpolicy Bypass -File "Deploy_PowerCLI_Silent.ps1 -MODE Install"
Powershell.exe -Executionpolicy Bypass -File "Deploy_PowerCLI_Silent.ps1 -MODE Uninstall"
[/code]

You will probably notice that to uninstall it silently you need to remove “VMware Remote Console Plug-in 5.1” followed by the “VMware vSphere PowerCLI” software.
The script build the arguments to do so, but if you are using a different version you will have to change:

[code language=”powershell”]$RemConsole = $InstalledProducts | where { $_.ARPDisplayName -eq "VMware Remote Console Plug-in 5.1" }[/code]

name to match
Just change the “VMware Remote Console Plug-in 5.1” portion to the same text as seen in your “Programs and Features” (Appwiz.cpl).
Make sure the VMware-PowerCLI.exe is in the same folder as the script.
The Script:

#########################################################################################################
#Script Name:   Deploy VMware PowerCLI 6.3 Silently                                                     #
#Script Author: SCCMOG - Richie Schuster 16/12/2016 WWW.SCCMOG.COM                                      #
#########################################################################################################
#Script Usage: "Deploy_PowerCLI_Silent.ps1 -Mode Install" to install and "-Mode Uninstall" to uninstall.#
#########################################################################################################

#Install Mode Parameter
PARAM (
    [string]$MODE
)

#If entery is input run script
If ($mode -ne $null){
    
    #If Mode input is Install run install.
    If ($MODE -eq "Install"){
        #Install VMware PowerCLI 6.3 Silently and Remote Console silently
        Start-Process "$PSScriptRoot\VMware-PowerCLI-6.3.0-3737840.exe" -ArgumentList '/b"C:\Windows\Temp" /VADDLOCAL=ALL /S /V"/qn ALLUSERS=1 REBOOT=ReallySuppress' -wait -NoNewWindow
        }
    #If Mode input uninstall run uninstall
    ElseIf ($MODE -eq "Uninstall"){
        ##Get all Applications in SMS namespace
        $InstalledProducts = Get-WmiObject -Namespace 'root\cimv2\sms' -Class SMS_InstalledSoftware

        #Grab PowerCLI related
        $RemConsole = $InstalledProducts | where { $_.ARPDisplayName -eq "VMware Remote Console Plug-in 5.1" }
        $PowerCLI = $InstalledProducts | where { $_.ARPDisplayName -eq "VMware vSphere PowerCLI" }

        #Get store local msi for uninstall arguements
        $REMCLP = $RemConsole.LocalPackage
        $PCLILP = $PowerCLI.LocalPackage

        #Get process that must be killed to uninstall silently
        $Running = Get-Process -Name vmware-usbarbitrator64 -ErrorAction SilentlyContinue

            #Check if process is running
            If ($Running -ne $null){
                #Kill process if it is
                Stop-Process -Name vmware-usbarbitrator64 -Force
                #Start Removal of VMware Remote Console Plug-in 5.1
                Start-Process "msiexec.exe" -ArgumentList "/x $REMCLP /qn /L*v $env:windir\temp\Uninstall_VMwareREMConsolePlg5.1.log /norestart" -wait -NoNewWindow
                #Start Removal of VMware vSphere PowerCLI
                Start-Process "msiexec.exe" -ArgumentList "/x $PCLILP /qn /L*v $env:windir\temp\Uninstall_VMwarevSpherePowerCLI.log /norestart" -wait -NoNewWindow
            }
            Else{
                #Start Removal of VMware Remote Console Plug-in 5.1
                Start-Process "msiexec.exe" -ArgumentList "/x $REMCLP /qn /L*v $env:windir\temp\Uninstall_VMwareREMConsolePlg5.1.log /norestart" -wait -NoNewWindow
                #Start Removal of VMware vSphere PowerCLI
                Start-Process "msiexec.exe" -ArgumentList "/x $PCLILP /qn /L*v $env:windir\temp\Uninstall_VMwarevSpherePowerCLI.log /norestart" -wait -NoNewWindow
            }
    }
    #If mode input does not match inform user.
    Else{
        Write-host 'Incorrect Params please format this way: "Deploy_PowerCLI_Silent.ps1 -Mode Install" to install and "-Mode Uninstall" to uninstall.'
    }
}
#If params are not specified then inform.
Else{
    Write-host 'Script Params must be used : "Deploy_PowerCLI_Silent.ps1 -Mode Install" to install and "-Mode Uninstall" to uninstall.'
    }
#########################################################################################################

Copyright 2016 SCCMOG | All Rights Reserved