Why you should not use the ConfigMgr rebuild index task — Steve Thompson [MVP]

Rebuilding the database indexes is a good thing, yes? Absolutely. Why not use the ConfigMgr rebuild index maintenance task? When the maintenance task works, and I have proof that some of the time it fails to run on ConfigMgr: It REINDEXES all indexes with more than 10% fragmentation It does not update statistics Let’s break […]

via Why you should not use the ConfigMgr rebuild index task — Steve Thompson [MVP]

Java Version Cleanup PowerShell Script

If you still have to maintain Java installations in your environment you will probably come up against having machines with multiple versions installed, unless you are running a clean up script for the old releases.

It is however sometimes a requirement to keep a specific release of Java for application compatibility, so what do you do in those scenarios where you want to clean up your old installs but the required version.

The below PowerShell script will do just that. It looks at your installed versions of Java, removes all previous versions and provides you with the option of specifying a version to keep during the process.

Script Download Link – https://gallery.technet.microsoft.com/scriptcenter/Java-Version-Cleaner-4a73f6be


<#
.NOTES
===========================================================================
Created with: SAPIEN Technologies, Inc., PowerShell Studio 2016 v5.2.128
Created on: 13/11/2016 22:13
Created by: Maurice.Daly
Organization:
Filename: JavaVersionCleaner.ps1
===========================================================================
.DESCRIPTION
This script removes previous versions of Oracle Java.
The script supports the option to specify specific versions to keep
during the uninstall process.
.EXAMPLE
.\JavaVersionCleaner.ps1 -MinJavaVersion jre1.8.0_100
Using this will keep the current version of Java and also jre1.8.0_100

.\JavaVersionCleaner.ps1
This will remove all versions bar the current version of Java
#>
[CmdletBinding(SupportsShouldProcess = $true)]
param (
[parameter(Mandatory = $false, HelpMessage = "Specify Java Version to maintain", Position = 1)]
[ValidateNotNullOrEmpty()]
[string]$MinJavaVersion
)

function JavaX64Uninstall ($MinJavaVersion)
{
Write-Debug "Running X64 Uninstalls"
# Read registry for Java 64 bit versions
$JavaX64Installs = Get-ChildItem -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall -Recurse | Get-ItemProperty | Where-Object { ($_.displayName -like "*Java*Update*") -and ($_.displayName -notlike "*Java*Auto*") } | Select Displayname, UninstallString, InstallDate, InstatallLocation
$JavaX64Count = $JavaX64Installs.Count

foreach ($JavaX64Install in ($JavaX64Installs | Sort-Object InstallDate))
{
if (($JavaX64Count) -gt 1)
{
if ($JavaX64Install.InstallLocation -notlike "*$($MinJavaVersion)*")
{
$MSIString = $JavaX64Install.Uninstallstring | Split-Path -Leaf
Write-Debug "Uninstalling $($JavaX64Install.Displayname)"
Write-Debug "MSIString $($MSIString)"
Start-Process MSIEXEC.EXE -ArgumentList (" /" + $MSIString + " /QN")
}
$JavaX64Count--
}
}
}

function JavaX86Uninstall ($MinJavaVersion)
{
Write-Debug "Running X86 Uninstalls"
# Read registry for Java 32 bit versions
$JavaX86Installs = Get-ChildItem -Path HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall -Recurse | Get-ItemProperty | Where-Object { ($_.displayName -like "*Java*Update*") -and ($_.displayName -notlike "*Java*Auto*") } | Select Displayname, UninstallString, InstallDate, InstallLocation
$JavaX86Count = $JavaX86Installs.Count
foreach ($JavaX86Install in ($JavaX86Installs | Sort-Object InstallDate))
{
if (($JavaX86Count) -gt 1)
{
if ($JavaX86Install.InstallLocation -notlike "*$($MinJavaVersion)*")
{
$MSIString = $JavaX86Install.UninstallString | Split-Path -Leaf
Write-Debug "Uninstalling $($JavaX86Install.Displayname)"
Write-Debug "MSIString $($MSIString)"
Start-Process MSIEXEC.EXE -ArgumentList (" /" + $MSIString + " /QN")
}
$JavaX86Count--
}
}
}

# Check for Windows 32 or 64 bit and process functions
if ((Test-Path -Path "C:\Program Files (x86)") -eq $true)
{
JavaX64Uninstall ($MinJavaVersion)
JavaX86Uninstall ($MinJavaVersion)
}else{
JavaX86Uninstall ($MinJavaVersion)
}

Staff Off-Boarding with Office 365

office-365

Over time in any environment the day will come around when the inevitable happens and staff leave. This happens due to lots of different reasons but there is often a question as to what to do with user accounts when this happens. This is particularly true in smaller companies with no set process for IT departments off-boarding staff.

In my own environment, I decided to set up a standard script which would work with Active Directory and Office 365 to achieve the following;

  1. Connects to your local DC for active directory functions and Office 365 for mailbox functions
  2. Disable the employee’s user account (verifies the user details before proceeding)
  3. Stamp details on the disabled user account with the IT person who disabled the account for audit purposes
  4. Move the disabled user account to a separate OU
  5. Disable all forms of remote mail access (OWA, ActiveSync, POP, etc)
  6. Set an Out of Office stating that the employee has left the company
  7. Place the mailbox into Legal hold for data retention purposes
  8. Hides the account from the GAL
  9. Emails the former employee’s manager advising that the account has been disabled

The user account is then maintained for a period of 30 days before being deleted and thus returning any assigned Office 365 licenses to the pool etc.

This might help to give you some ideas about setting up your own scripting process for dealing with this issue.

Script Download Link – https://gallery.technet.microsoft.com/scriptcenter/Staff-Off-Boarding-Script-430bdd0a


<#
.NOTES
===========================================================================
Created with: SAPIEN Technologies, Inc., PowerShell Studio 2016 v5.2.128
Created on: 04/11/2016 21:00
Created by: Maurice Daly
Filename: DisableUserOffice365.ps1
===========================================================================
.DESCRIPTION
This script provides a standard off-boarding method for staff leaving
the company.

The script does the following;
1. Disables the specified user account
2. Updates the user description with the user who disabled the account
and the time/date when the account was disabled
3. Moves the account to the disabled user account OU (needs to exist)
4. Sets an out of office reply stating that the employee has left the company
5. Disables activesync, pop3, imap etc
6. Places mail account into legal hold for 7 years (requires Office 365 E3)
7. Hides the mail account from the GAL
8. Emails the former employee's manager advising that the account has been disabled

Version 1.0
Initial release

Use : This script is provided as it and I accept no responsibility for
any issues arising from its use.

Twitter : @modaly_it
Blog : https://modalyitblog.wordpress.com/
#>

Write-Host " **************** PLEASE ENTER ACTIVE DIRECTORY ADMIN CREDENTIALS **************** "
$Credential = Get-Credential -Credential "$env:USERDOMAIN\$env:USERNAME"
$DC = $env:LOGONSERVER.Substring(2)

#Initiate Remote PS Session to local DC
$ADPowerShell = New-PSSession -ComputerName $DC -Authentication Negotiate -Credential $Credential

# Import-Module ActiveDirectory
write-host "Importing Active Directory PowerShell Commandlets"
Invoke-Command -Session $ADPowerShell -scriptblock { import-module ActiveDirectory }
Import-PSSession -Session $ADPowerShell -Module ActiveDirectory -AllowClobber -ErrorAction Stop

# Retrieve AD Details
$ADDetails = Get-ADDomain
$Domain = $ADDetails.DNSRoot
Clear-Host

write-host "Importing Office 365 PowerShell Commandlets"
Write-Host -ForegroundColor White -BackgroundColor DarkBlue " **************** PLEASE ENTER OFFICE 365 ADMIN CREDENTIALS **************** "
$Office365Credential = Get-Credential
$Office365PowerShell = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $Office365Credential -Authentication Basic -AllowRedirection
Import-PSSession $Office365PowerShell
Clear-Host

write-host " **************** Disable Active Directory User Account & Enable Out Of Office **************** "
write-host " "

# Get Variables
$DisabledDate = Get-Date
$LeaveDate = Get-Date -Format "dddd dd MMMM yyyy"
$DisabledBy = Get-ADUser "$env:username" -properties Mail
$DisabledByEmail = $DisabledBy.Mail

# Prompt for AD Username
$Employee = Read-Host "Employee Username"
$EmployeeDetails = Get-ADUser $Employee -properties *
If ($EmployeeDetails.Manager -ne $null)
{
$Manager = Get-ADUser $EmployeeDetails.Manager -Properties Mail
}

Clear-Host

# Prompt for confirmation
write-host " ******************************** CONFIRM USER DISABLE REQUEST ******************************** "
write-host " "
write-host -ForegroundColor Yellow "Please review the Employee details below to ensure you are disabling the correct user account."
$EmployeeDetails | fl Name, Title, Company, @{ Expression = { $_.mail }; Label = "Email Address" }, @{Expression = { $_.Created }; Label = "Employment Started"}

$choice = " "
while ($choice -notmatch "[y|n]")
{
$choice = read-host "Do you want to continue? (Y/N)"
}

# Actions
if ($choice -eq "y")
{
Clear-Host
write-host " ******************************** DISABLING USER ACCOUNT ******************************** "
write-host " "
write-host "Step1. Modifying user description for audit purposes" -ForegroundColor Yellow
Set-ADUser $Employee -Description "Disabled by $($DisabledBy.name) on $DisabledDate"
write-host "Step2. Disabling $Employee Active Directory Account." -ForegroundColor Yellow
Disable-ADAccount $Employee
write-host "Step3. Moving $Employee to the Disabled User Accounts OU." -ForegroundColor Yellow
write-host " "
Move-ADObject -Identity $EmployeeDetails.DistinguishedName -targetpath "OU=Disabled User Accounts,DC=YOURDOMAIN,DC=SUFFIX"
write-host "Waiting 5 seconds for AD & Exchange OU update to complete"
sleep -Seconds 5
write-host " "
write-host "Refreshing Employee Details for Exchange Modification."
write-host " "
Get-ADUser $Employee -Properties Description | Format-List Name, Enabled, Description
write-host "Step 4. Setting Exchange Out Of Office Auto-Responder." -ForegroundColor Yellow
Set-MailboxAutoReplyConfiguration -Identity $EmployeeDetails.Mail -AutoReplyState enabled -ExternalAudience all -InternalMessage "Please note that I no longer work for $($EmployeeDetails.company) as of $LeaveDate." -ExternalMessage "Please note that I no longer work for $($EmployeeDetails.company) as of $LeaveDate. Direct all correspondence to info@yourdomain.suffix."
Write-Host "Step 5. Disabling POP,IMAP, OWA and ActiveSync access for $User" -ForegroundColor Yellow
Set-CasMailbox -Identity $EmployeeDetails.mail -OWAEnabled $false -POPEnabled $false -ImapEnabled $false -ActiveSyncEnabled $false
Write-Host "Step 6. Placing mailbox $($EmployeeDetails.name) into Ligitgation hold for 7 years" -ForegroundColor Yellow
Set-Mailbox -Identity $EmployeeDetails.mail -LitigationHoldEnabled $true -LitigationHoldDuration 2555
Write-Host "Step 7. Hiding $($EmployeeDetails.name) from Global Address lists" -ForegroundColor Yellow
Set-ADUser -identity $Employee -add @{ msExchHideFromAddressLists = "True" }
Set-ADUser -instance $EmployeeDetails -whatif
If ($Manager.Mail -like "*@*")
{
Write-Host "Step 8. Sending Confirmation E-mail To Employee's Manager." -ForegroundColor Yellow
$msg = new-object Net.Mail.MailMessage
$smtp = new-object Net.Mail.SmtpClient("youroffice365mailserveraddress")
$msg.From = "Support@yourdomain.suffix"
$msg.To.Add("$($Manager.Mail)")
$msg.subject = "IT Notification - Employee Leaver Confirmation"
$msg.body = "This email is confirm that $($EmployeeDetails.Name)'s account has been disabled. An out of office notification advising that $($EmployeeDetails.Name) has left the company has also been set. Note that the account will be deleted after 30 days."
$smtp.Send($msg)
}
}else{
write-host " "
write-host "Employee disable request cancelled" -ForegroundColor Yellow
}

 

SCCM Viglen Client Driver Autodownload PowerShell Script

viglen

In October of 2016 I released a script that downloaded drivers and bios updates for Dell client systems and created associated driver packs in SCCM (https://modalyitblog.wordpress.com/2016/10/10/sccm-dell-client-bios-driver-autodownload-ps-script/).

A friend of mine works in the UK educational system as an admin and thought it would be nice to have a similar script for his environment, mainly consisting of the UK educational hardware builder Viglen.

So here is version 1.0 of the download script adjusted for Viglen client systems.

The below scripts requires you to specify your driver file share and your SCCM site server name as a variable, it then does the following;

  1. Queries SCCM for a full list of Viglen client products
  2. Downloads the driver INF zip file for each model
  3. Extract the driver INF zip
  4. Import the drivers in the extracted ZIP folder
  5. Create a Category based on the machine model
  6. Create a Driver Package based on the machine model
  7. Imports the associated drivers into the newly created Driver Package

The downloads are stored within sub-folders within the share you specified, e.g;

\\MySCCMServer\Drivers\Viglen 820s\Driver ZIP\
\\MySCCMServer\Drivers\Viglen 820s\Extracted Drivers\

This slideshow requires JavaScript.

PowerShell Script

To run the script use the following syntax;

.\ViglenSCCMDownload.ps1 -SiteServer YOURSITESERVER -RepositoryPath “\\YOURSERVER\DRIVERREPO\” -PackagePath “\\YOURSERVER\DRIVERPACKPATH”

The script has Windows 10 x64 specified, however you can change this under the #Define Operating Systems section. Note I have tested Windows 7 & 10 only during building this.


<#
.NOTES
===========================================================================
Created with: SAPIEN Technologies, Inc., PowerShell Studio 2016 v5.2.128
Created on: 03/11/2016 13:00
Created by: Maurice Daly
Filename: ViglenSCCMDownloads.ps1
==========================================================================
.DESCRIPTION
This script allows you to automate the process of keeping your
driver sources up to date. The script reads the Viglen support download
site for models found within SCCM and then downloads the corresponding
drivers

Version 1.0
Initial release

Notes
You can skip the driver package creation process by changing the
$DriverPackageCreation variable to $False.
The system architecture can also be changed by modifying the
$Architecture variable and using x64 or x86
You can limit the number of concurrent jobs by specifying
your max value in the $MaxConcurrent jobs variable

To run the script use the following syntax;

.\ViglenSCCMDownload.ps1 -SiteServer YOURSITESERVER -RepositoryPath UNCTEMPDRIVERPATH -PackagePath UNCDRIVERPACKAGEPATH

To re-enable error messaging for troubleshooting purpose
comment out the Error and Warning Preference values below

Use : This script is provided as it and I accept no responsibility for
any issues arising from its use.

Twitter : @modaly_it
Blog : https://modalyitblog.wordpress.com/
#>

# Define SCCM Site Server
[CmdletBinding(SupportsShouldProcess = $true)]
param (
[parameter(Mandatory = $true, HelpMessage = "Site server where the SMS Provider is installed", Position = 1)]
[ValidateNotNullOrEmpty()]
[ValidateScript({ Test-Connection -ComputerName $_ -Count 1 -Quiet })]
[string]$SiteServer,
[parameter(Mandatory = $true, HelpMessage = "UNC path for downloading and extracting drivers")]
[ValidateNotNullOrEmpty()]
[ValidateScript({ Test-Path $_ })]
[string]$RepositoryPath,
[parameter(Mandatory = $true, HelpMessage = "UNC path of your driver package repository")]
[ValidateNotNullOrEmpty()]
[ValidateScript({ Test-Path $_ })]
[string]$PackagePath
)

$ErrorActionPreference = 'SilentlyContinue'
$WarningPreference = 'SilentlyContinue'

# Import SCCM PowerShell Module
Import-Module "C:\Program Files (x86)\Microsoft Configuration Manager\AdminConsole\bin\ConfigurationManager.psd1"

# Define Maximum Number Of Simultaneously Running Jobs
$MaxConcurrentJobs = 5

# Query SCCM Site Code
function QuerySiteCode ($SiteServer)
{
Write-Verbose "Determining SiteCode for Site Server: '$($SiteServer)'"
$SiteCodeObjects = Get-WmiObject -Namespace "root\SMS" -Class SMS_ProviderLocation -ComputerName $SiteServer -ErrorAction Stop
foreach ($SiteCodeObject in $SiteCodeObjects)
{
if ($SiteCodeObject.ProviderForLocalSite -eq $true)
{
$SiteCode = $SiteCodeObject.SiteCode
Write-Debug "SiteCode: $($SiteCode)"

}
}
Return [string]$SiteCode
}

function QueryModels ($SiteCode)
{
# ArrayList to store the Viglen models in
$ViglenProducts = New-Object -TypeName System.Collections.ArrayList
# Enumerate through all models
#$Models = "VIG430P","VIG665W","Vig670W","Vig800S","Vig820S","Vig830S"
$Models = Get-WmiObject -Namespace "root\SMS\site_$($SiteCode)" -Class SMS_G_System_COMPUTER_SYSTEM | Select-Object -Property Model | Where-Object { $_.Model -like "*Vig*" }
# Add model to ArrayList if not present
if ($Models -ne $null)
{
foreach ($Model in $Models)
{
if ($Model.Model -notin $ViglenProducts)
{
$ViglenProducts.Add($Model.Model) | Out-Null
}
}
}
#$ViglenProducts = "VIG430P", "VIG665W", "Vig670W", "Vig800S", "Vig820S", "Vig830S"
Return $ViglenProducts
}

function StartDownloadAndPackage ($PackagePath, $RepositoryPath)
{
$RunDownloadJob = {
Param ($Model,
$SiteCode,
$PackagePath,
$RepositoryPath)

# =================== DEFINE VARIABLES =====================

# Directory used for driver downloads
$DriverRepositoryRoot = ($RepositoryPath.Trimend("\") + "\Viglen\")
Write-Host "Driver package path set to $DriverRepositoryRoot"

# Directory used by SCCM for driver package
$DriverPackageRoot = ($PackagePath.Trimend("\") + "\Viglen\")
Write-Host "Driver package path set to $DriverPackageRoot"

# Define Operating System
$OperatingSystem = "Windows"
$OperatingSystemVersion = "10"
$Architecture = "64"

# Define Viglen Download Sources
$ViglenBaseURL = "http://download.viglen.co.uk"
$ViglenDownloadList = "/files/Motherboards/"
$ViglenBIOSFolder = "BIOS/"
$ViglenDriverFolder = "Drivers/"

# Import Driver Packs?
$DriverPackCreation = $true

# Import SCCM PowerShell Module
Import-Module "C:\Program Files (x86)\Microsoft Configuration Manager\AdminConsole\bin\ConfigurationManager.psd1"

# =================== INITIATE DOWNLOADS ===================

Write-Host "Getting download URL for Viglen client model: $Model"
$ModelLink = (Invoke-WebRequest -Uri ($ViglenBaseURL + $ViglenDownloadList) -UseBasicParsing).Links | Where-Object { $_.href -like "*$Model*" }
$ModelURL = ($ViglenBaseURL + $ModelLink.href)

# Correct slash direction issues
$ModelURL = $ModelURL.Replace("\", "/")

# ============= SCCM Driver Cab Download ==================

Write-Host "Getting SCCM driver pack link for model: $Model"
$ViglenInfFolder = (((Invoke-WebRequest -Uri ($ModelURL + $ViglenDriverFolder) -UseBasicParsing).links | Where-Object { $_.href -like "*INF*" }).href | Split-Path -Leaf) + "/"
$SCCMDriverDownload = ((Invoke-WebRequest -Uri ($ModelURL + $ViglenDriverFolder + $ViglenInfFolder) -UseBasicParsing).Links | Where-Object { $_.href -like "*$($OperatingSystem.trim("dows"))*$OperatingSystemVersion*.zip" } | Select-Object -Last 1).href
if ($SCCMDriverDownload -eq $null)
{
# Check for driver folder for specified OS
$DriverOSSubFolder = ((Invoke-WebRequest -Uri ($ModelURL + $ViglenDriverFolder + $ViglenInfFolder) -UseBasicParsing).Links | Where-Object { $_.outerHTML -like "*$OperatingSystem*$OperatingSystemVersion*" }).href | Split-Path -Leaf
if ($DriverOSSubFolder -eq $null)
{
Write-Host -ForegroundColor White -BackgroundColor Red "Driver does not exist for $Model running $OperatingSystem $OperatingSystemVersion"
Break
}
else
{
$SCCMDriverDownload = ((Invoke-WebRequest -Uri ($ModelURL + $ViglenDriverFolder + $ViglenInfFolder + $DriverOSSubFolder) -UseBasicParsing).Links | Where-Object { $_.href -like "*$($OperatingSystem.trim("dows"))*$OperatingSystemVersion*.zip" } | Select-Object -Last 1).href
}
}
else
{
# $SCCMDriverDownload = $SCCMDriverDownload.href
}

$SCCMDriverZIP = ($SCCMDriverDownload | Split-Path -Leaf)

# Check for destination directory, create if required and download the driver zip
if ((Test-Path -Path ($DriverRepositoryRoot + $Model + "\Driver ZIP\")) -eq $true)
{
if ((Test-Path -Path ($DriverRepositoryRoot + $Model + "\Driver ZIP\" + $SCCMDriverZIP)) -eq $true)
{
Write-Host -ForegroundColor Yellow "Skipping $SCCMDriverZIP... File already downloaded..."
$SkipDriver = $true
}
else
{
Start-BitsTransfer -Source ($ViglenBaseURL + $SCCMDriverDownload) -Destination ($DriverRepositoryRoot + $Model + "\Driver ZIP\" + $SCCMDriverZIP) -DisplayName "Downloading $Model driver ZIP file"
$SkipDriver = $false
}
}
else
{
Write-Host -ForegroundColor Green "Creating $Model download folder"
New-Item -Type dir -Path ($DriverRepositoryRoot + $Model + "\Driver ZIP")
Start-BitsTransfer -Source ($ViglenBaseURL + $SCCMDriverDownload) -Destination ($DriverRepositoryRoot + $Model + "\Driver ZIP\" + $SCCMDriverZIP) -DisplayName "Downloading $Model driver ZIP file"
}

# =================== CREATE DRIVER PACKAGE AND IMPORT DRIVERS ===================

Write-Host -ForegroundColor Green "Starting extract and import process"
$DriverSourceFile = ($DriverRepositoryRoot + $Model + "\Driver ZIP\" + $SCCMDriverZIP)
$DriverExtractDest = ($DriverRepositoryRoot + $Model + "\Extracted Drivers")
$DriverPackageDir = ($DriverSourceFile | Split-Path -Leaf)
$DriverPackageDir = $DriverPackageDir.Substring(0, $DriverPackageDir.length - 4)
$DriverFileDest = $DriverPackageRoot + "Viglen\" + $DriverPackageDir

if ($DriverPackCreation -eq $true)
{
if ((Test-Path -Path $DriverExtractDest) -eq $false)
{
New-Item -Type dir -Path $DriverExtractDest
}
else
{
Get-ChildItem -Path $DriverExtractDest -Recurse | Remove-Item -Recurse -Force
}
New-Item -Type dir -Path $DriverFileDest
Set-Location -Path ($SiteCode + ":")
$CMDDriverPackage = "Viglen " + $Model + " " + $OperatingSystem + " " + $OperatingSystemVersion + " " + $Architecture + "bit"
if (Get-CMDriverPackage -Name $CMDDriverPackage)
{
Write-Host -ForegroundColor Yellow "Skipping.. Driver package already exists.."
}
else
{
Write-Host -ForegroundColor Green "Creating driver package"
Set-Location -Path $env:SystemDrive
Add-Type -assembly "system.io.compression.filesystem"
[io.compression.zipfile]::ExtractToDirectory($DriverSourceFile, $DriverExtractDest)
$DriverINFFiles = Get-ChildItem -Path $DriverExtractDest -Recurse -Filter "*.inf"
}
Set-Location -Path ($SiteCode + ":")
New-CMDriverPackage -Name $CMDDriverPackage -path ($DriverPackageRoot + $Model + "\" + $OperatingSystem + " " + $OperatingSystemVersion + "\" + $Architecture)
if (Get-CMCategory -CategoryType DriverCategories -name ("Viglen " + $Model))
{
Write-Host -ForegroundColor Yellow "Category already exists"
$DriverCategory = Get-CMCategory -CategoryType DriverCategories -name ("Viglen " + $Model)
}
else
{
Write-Host -ForegroundColor Green "Creating category"
$DriverCategory = New-CMCategory -CategoryType DriverCategories -name ("Viglen " + $Model)
}
$DriverPackage = Get-CMDriverPackage -Name $CMDDriverPackage
foreach ($DriverINF in $DriverINFFiles)
{
$DriverInfo = Import-CMDriver -UncFileLocation ($DriverINF.FullName) -ImportDuplicateDriverOption AppendCategory -EnableAndAllowInstall $True -AdministrativeCategory $DriverCategory | Select-Object *
Add-CMDriverToDriverPackage -DriverID $DriverInfo.CI_ID -DriverPackageName $CMDDriverPackage
}
}
Set-Location -Path $env:SystemDrive
}
$TotalModelCount = $ViglenProducts.Count
$RemainingModels = $TotalModelCount
foreach ($Model in $ViglenProducts)
{
write-progress -activity "Initiate Driver Download & Driver Package Jobs" -status "Progress:" -percentcomplete (($TotalModelCount - $RemainingModels)/$TotalModelCount * 100)
$RemainingModels--
$Check = $false
while ($Check -eq $false)
{
if ((Get-Job -State 'Running').Count -lt $MaxConcurrentJobs)
{
Start-Job -ScriptBlock $RunDownloadJob -ArgumentList $Model, $SiteCode, $PackagePath, $RepositoryPath -Name ($Model + " Download")
$Check = $true
}
}
}
Get-Job | Wait-Job | Receive-Job
Get-Job | Remove-Job
}


# Get SCCM Site Code
$SiteCode = QuerySiteCode ($SiteServer)

Write-Debug $PackagePath
Write-Debug $RepositoryPath

if ($SiteCode -ne $null)
{
# Query Viglen Products in SCCM using QueryModels function
$ViglenProducts = QueryModels ($SiteCode)
# Output the members of the ArrayList
if ($ViglenProducts.Count -ge 1)
{
foreach ($ModelItem in $ViglenProducts)
{
$PSObject = [PSCustomObject]@{
"Viglen Models Found" = $ModelItem
}
Write-Output $PSObject
}
}
# Start download, extract, import and package process
Write-Host -ForegroundColor Green "Starting download, extract, import and driver package build process.."
StartDownloadAndPackage ($PackagePath) ($RepositoryPath) ($SiteCode)
}