Matching items using Import-CSV + environment variables

by fangol at 2013-01-01 14:00:38

Hi

I’m new to PowerShell so please bear with me! I am trying to modify an existing script which retrieves an IP address from end clients then attempts to match it against a column of CIDR IP addresses in a CSV file using Import-CSV. If the IP address falls within a subnet listed in one column in the csv file then the user is added to an AD group (listed in another column in the csv) . I need to update the script to set an environment variable if the client IP address does not fall within the subnets listed in the CSV. If it can find a match I need it to pull two corresponding values from two other columns in the CSV then set these as environment variables. Can anyone advise the easiest way of doing this? Assuming I should use [Environment]::SetEnvironmentVariable command but not sure how I can get it to add the two values from the CSV as environment variables.

Thanks
by DonJ at 2013-01-01 14:27:55
SetEnvironmentVariable will only modify the variable in the current PowerShell process, not globally for the system. In general, applications aren’t allowed to make global changes to the environment variables.
by Infradeploy at 2013-01-02 00:44:44
System environment variables can be edited in the registry:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment
by fangol at 2013-01-02 07:58:00
Thanks guys, creating a temporary environment variable is fine for what we need. BUt how do I add two values from a the CSV? There are two columns of data that need to be added together and set as the environment variable. e.g.

If the CSV contains Column 3, Column 4 and I wanted to add a process environment variable would it be :-


SetEnvironmentVariable("$.EnvVariable", "$.Column3.+$Column4", “Process”)
by DonJ at 2013-01-02 08:02:55
Sort of. You can’t use variables in double quotes quite like that.

"$($variable.property)"

You have to use a subexpression, which means surrounding the expression with $().

"$($
.Column3)$($.Column4)“
by fangol at 2013-01-04 10:37:15
Hi Don, thanks very much for your help! Last Question. Can you recommend any PowerShell tutorials?
Dan
by RichardSiddaway at 2013-01-05 04:57:35
If you are starting with PowerShell then I would recommend Don’s book - Learning PowerShell in a Month of Lunches. There is a new edition for PowerShell v3. Check the links on the books page
by fangol at 2013-01-08 05:03:35
Great thanks Richard!
by fangol at 2013-01-11 08:29:31
Hi Guys

I’m still having issues with my script and wondered if anyone could help out? It’s telling me that on line 496 the FindCorrectVM command is not recognised as a cmdlet or function. I know the original script worked (that I copied this from) so I’m wondering if I’ve got the set environment variable command wrong?

Thanks
Dan



# The Global variables are used throughout the script and define the script behaviour
# Change the $Global:Debug value to “True” to enable script logging and configure the
# log file location


#*******************************************************************
# Global Variables
#*******************************************************************
$Global:Debug = “True”
$Global:Version = ‘1.0’
$Global:LogSeparator = ‘
$Global:LogFile = “C:\CustomerScript\branchprinter.log”
$Global:CitrixThinClientRegKey = “Citrix\VirtualDesktopAgent\State”
$Global:CitrixThinClientRegString = “clientaddress”
$Global:BranchPrefixRegKey = “PCBase\Config\32bit\PC6”
$Global:BranchPrefixRegString = “BranchNo”
$Global:MappingFileName = “Mapping.csv”
$Global:LocalMappingFileDirectory = “C:\CustomerScript”
$Global:BuildTypeRegKey = “Policies\Customer\PCBase\Profile”
$Global:BuildTypeRegString = “SWProfile”
$Global:BuildTypeRegValue = @(“VDI_Front_Office”, “VDI_Branch_Client”, “VDI_OLB”, “VDI_IMC_Client”, “VDI_IMC_Front_Office”, “VDI_Area_Office”, “VDI_Housing”)
$Global:BOSSInstallPath = “C:\Program Files\Journal Viewer\JournalViewerShell.exe”
$Global:PodiumGroup = “MSScriptTest05”
$Global:ADGroupOU = “OU=Test Groups,OU=VDI Script Test,OU=Windows XP VDI Clients”


#

# Functions
#
****************************************************

function Get-ScriptDirectory {

#
# DESCRIPTION
# Extracts the script directory to locate mapping file
#

$Invocation = (Get-Variable MyInvocation -Scope 1).Value
Split-Path $Invocation.MyCommand.Path
}



function Get-ScriptName(){
#
# DESCRIPTION
# Extracts the script file name without extension
#
$tmp = $MyInvocation.ScriptName.Substring($MyInvocation.ScriptName.LastIndexOf(’’) + 1)
$tmp.Substring(0,$tmp.Length - 4)

} #End Function


function Write-Log($Msg){
#
# DESCRIPTION
# Creates a log entry with time stamp if the Debug variable is set to True
#

If ($Global:Debug -eq “True”)

{

$date = Get-Date -format dd.MM.yyyy
$time = Get-Date -format HH:mm:ss
Add-Content -Path $LogFile -Value ($date + " " + $time + " " + $Msg)

}

} #End Function

function Initialise-LogFile($File){
#
# DESCRIPTION
# Initialises the log file and creates the log file header
#

try{
#Check if file exists
if(Test-Path -Path $File){

#Check if file is a local file
if($File.Substring(1,1) -eq ‘:’){

#Check if drive exists
$driveInfo = System.IO.DriveInfo

if($driveInfo.IsReady -eq $false){

Write-Log -Msg ($driveInfo.Name + " not ready.”)}

#Create folder structure if necessary
$Dir = [System.IO.Path]::GetDirectoryName($File)

if(([System.IO.Directory]::Exists($Dir)) -eq $false){

$objDir = [System.IO.Directory]::CreateDirectory($Dir)
Write-Log -Msg ($Dir + " created.")
}
}
}

#Write header
Write-Log -Msg $LogSeparator
Write-Log -Msg ("Script Name: " + ((Get-ScriptName) + " (Version: " + $Version + “)”))

}
catch{
Write-Log -Msg $

}
} #End Function



function Failsafe () {
#
# DESCRIPTION
# If the VM information cannot be determined or validated, we add the user to the Podium Group and issue a warning message on screen
# instructing the user to call the Helpdesk.
#

Write-Log -Msg “Failsafe has been started - attempting to add user to Podium Group”


#Add the user to the Podium Group
If((AddRemoveUser-Group -Action “Add” -GroupName $Global:PodiumGroup) -eq “Success”) {

Write-Log -Msg “The user has been added to the podium group”


#Use GenerateForm function to display message to user
$message = $message = “We have been unable to assign a session appropriate for your branch, you will now be logged out of this session. Once logged out, please ‘Sign Out’ from your Thin Client device and restart the log in process to access a session with limited functionality. Please contact the IT Service Desk and tell them that the system is unable to assign you to a session appropriate for your branch.”

GenerateForm $message

Write-Log -Msg “Failsafe process complete. The user will now be logged off”
Write-Log -Msg $LogSeparator
Write-Log -Msg ‘Logon Script Completed…’


#After the user has clicked OK to the message, logoff the user and Exit

If ($Global:Debug -ne “True”) {

shutdown -l -f
}
Exit
}


#If the user could not be added to the Podium Group, this needs to be captured.
Else {

Write-Log -Msg “The user could not be added to the podium group”


#Use GenerateForm function to display message to user
$message = “We have been unable to assign a session appropriate for your branch, please log out and restart the log in process. If this problem persists, please contact the IT Service Desk and tell them that the system is unable to assign you to a session appropriate for your branch.”

GenerateForm $message

Write-Log -Msg “Failsafe process complete. The user will now be logged off”
Write-Log -Msg $LogSeparator
Write-Log -Msg ‘Logon Script Completed…’


#After the user has clicked OK to the message, logoff the user and Exit

If ($Global:Debug -ne “True”) {

shutdown -l -f

}
Exit
}
} #End Function

function Log-Event($message) {

#
# DESCRIPTION
# Writes an event to the Windows Application Log
#

Write-EventLog -LogName Application -message $message -source “Winlogon” -id “1234”

}


function Validate-Machine() {

#
# DESCRIPTION
# 1. Determines whether the machine is virtual
# 2. Determines whether the D: Partition is available
# 3. Determines whether BOSS is installed
# 4. Determines the build type
#

Write-Log -Msg $LogSeparator
Write-Log -Msg ‘Validating Machine’

#Check if this is a virtual machine

If ((Get-WmiObject Win32_ComputerSystem).Model -eq “Virtual Machine”) {

Write-Log -Msg “Computer confirmed as Virtual Machine”}

Else {

Write-Log -Msg “Computer is not a Virtual Machine or computer model cannot be determined.”
Write-Log -Msg $LogSeparator
Write-Log -Msg ‘Computer model cannot be determined…’
Exit}



#Check that the D: drive is available

if(Test-Path -Path "D:"){

Write-Log -Msg “D Parition is available” }

else {

Write-Log -Msg "D Parition is not available "
Exit}


<#Check if BOSS is installed

If (test-path -path $Global:BOSSInstallPath) {

Write-Log -Msg (“The BOSS program : " + $Global:BOSSInstallPath + " has been found. BOSS is installed.”)}

Else{

Write-Log -Msg (“The BOSS program : " + $Global:BOSSInstallPath + " has not been found. BOSS is not installed. Proceeding to Logon”)
Write-Log -Msg $LogSeparator
Write-Log -Msg ‘Logon Script Completed…’
Exit }


#>

<#Check BuildType

$BuildType = (Get-ItemProperty -path ("HKLM:\Software&quot; + $Global:BuildTypeRegKey)).$Global:BuildTypeRegString

Foreach ($i in $Global:BuildTypeRegValue) {

If ($BuildType -eq $i) {

Write-Log -Msg ("Build Type Match: The build type is " + $BuildType + “. Continuing script processing”)
$BuildTypeFound = “True”
Break
}
} #End ForEach

If ($BuildTypeFound -ne “True”) {

Write-Log -Msg (“The build type is " + $BuildType + " and is not a Branch build. Proceeding with logon”)
Write-Log -Msg $LogSeparator
Write-Log -Msg ‘Logon Script Completed…’
Exit} #>
} #Exit Function





function MappingFile() {

#
# DESCRIPTION
# Compare the central and local mapping files. Updates the local file if server copy is more recent.
# If the local mapping file does not exist, it will be coped from the central location. If no action is required
# then local mapping file is used.
#


$CentralMappingFile = ($Global:CentralMappingFileDirectory + "&quot; + $Global:MappingFileName)


Write-Log -Msg ("The central mapping file has been found at " + $CentralMappingFile)


#Check the local mapping file exists. If not perform actions to copy it from central source
if(!(Test-Path -Path $Global:LocalMappingFile)) {

Write-Log -Msg “The local mapping file could not be found.”


#As the local mapping file is not present, check the directory is present. If not create it.

If (!(Test-Path -Path $Global:LocalMappingFileDirectory))
{
Write-Log -Msg ("The local mapping file directory does not exist: " + $Global:LocalMappingFileDirectory)

New-Item $Global:LocalMappingFileDirectory -type directory

}



#As the local mapping file does not exist, attempt to copy from central source

If(Test-Path -Path $CentralMappingFile) {

Write-Log -Msg “Unable to locate the local mapping file… Proceeding to copy for central location”

Copy-Item $CentralMappingFile $Global:LocalMappingFile -force


#Retest to confirm file has been copied. If the file cannot be copied we load the failsafe.

If(Test-Path -Path $Global:LocalMappingFile) {

Write-Log -Msg “The local mapping has now been found.”}

Else {

#As the file still does not exist, assume it has been failed

Write-Log -Msg “Unable to locate the local mapping file after copy attempt. We will use the server copy”

#Update the LocalMappingFile variable with the Central variable to allow us to use the central copy
$Global:LocalMappingFile = $CentralMappingFile

}
}


Else
{

#We could not find a local file and the central file could not be used. Load the Failsafe
Write-Log -Msg “Both Local and Central Mapping Files could not be found. Loading the Failsafe”
#Failsafe
}



}

#Else if the local mapping file does exists. Check it is up to date.
Else {


#Compare the LastWriteTimeUTC attributes of the Central and Local Mapping Files

$CentralMappingFileUTC = (gci $CentralMappingFile).LastWriteTimeUTC

Write-Log -Msg ("The central mapping file last write timestamp(UTC) is " + $CentralMappingFileUTC)

$LocalMappingFileUTC = (gci $Global:LocalMappingFile).LastWriteTimeUTC

Write-Log -Msg ("The local mapping file last write timestamp(UTC) is " + $LocalMappingFileUTC)


#If the LastWriteTimeUTC value of the central mapping file is later than the local mapping file, delete the local file and copy the new version from the server.

If ($CentralMappingFileUTC -gt $LocalMappingFileUTC) {

Write-Log -Msg (“The central and local mapping files do not match - Copying the central mapping file to” + $Global:LocalMappingFile)

Copy-Item $CentralMappingFile $Global:LocalMappingFile -force }

#Otherwise we use the local mapping file

Else {

Write-Log -Msg “The local mapping file is up to date - Using local mapping file”}

} #End Else

} #Exit Function


function Gather-Information () {

#
# DESCRIPTION
# Extract the Thin Client IP address from the registry key on the VM. Use the IP Address and pass to the ConfirmCorrectVM function to
# determine whether the user is logging onto the correct VM.
#

#Identify the OS Architecture and identify the Thin Client IP Address. The key is maintained in different locations for x86 and x64 systems.


If ((Get-WmiObject Win32_OperatingSystem).OSArchitecture -eq “64-bit”) {

#Get the IP Address of the Thin Client connecting the VM
$CitrixThinClientIP = (Get-ItemProperty -path ("HKLM:\Software\WOW6432Node&quot; + $CitrixThinClientRegKey)).$CitrixThinClientRegString

}

Else {

$CitrixThinClientIP = (Get-ItemProperty -path ("HKLM:\Software&quot; + $CitrixThinClientRegKey)).$CitrixThinClientRegString

}

#Get the IP Address of the Thin Client connecting the VM


If ($CitrixThinClientIP) {

Write-Log -Msg ("Operating System Installed: " + (Get-WmiObject Win32_OperatingSystem).Caption)
Write-Log -Msg ("The Citrix Thin Clint IP Address is : " + $CitrixThinClientIP)}

Else {

#If we are unable to read the IP Address from the registry key, we need to load the failsafe

Write-Log -Msg (“Unable to identify the Citrix Thin Client IP Address”) }

#Load the failsafe procedure
#Failsafe}


#Locate the Branch Prefix from the registry on the VM. This will be used to determine whether the IP Address of the Thin Client is valid for that Branch
$BranchPrefix = ((Get-ItemProperty -path ("HKLM:\Software&quot; + $Global:BranchPrefixRegKey)).$Global:BranchPrefixRegString)


#Check if the branch prefix exists in the registry or if it contains the AppSense placeholder.

If ($BranchPrefix -eq $Null -or $BranchPrefix -match “%”) {

Write-Log -Msg “The branch prefix registry key does not exist or is invalid.”
#Failsafe
}


Write-Log -Msg ("Found branch prefix in registry: " + $BranchPrefix)
#If the branch prefix does not exist or is set to a value of 9999 we need to loop and wait for it to update.

#Now check the user is on the correct VM
Write-Log -Msg “Now to check the user is on the correct VM”

#Call the ConfirmCorrectVM function and pass the Branch Prefix and Thin Client IP Address extracted from the registry.

$Success = ConfirmCorrectVM -Prefix $BranchPrefix -ThinClientIP $CitrixThinClientIP


#If the ConfirmCorrectVM function has returned a success value, the VM is approved for that branch and logon completes.

If ($Success -eq “True”) {

Write-Log -Msg “The VM is approved for use from this Thin Client.”
Write-Log -Msg $LogSeparator
Write-Log -Msg ‘Completed…’
Exit}

#If the VM is not approved for that branch, the user is removed from the corresponding Active Directory Security Group
#We then need to determine which VMs the branch Thin Client should use - and add the user to the corresponding group

Else {Write-Log -Msg “The VM that the user has logged onto is not approved from the branch.”

If ((FindCorrectVM -ThinClientIP $CitrixThinClientIP) -eq “Success”) {

$message = “We notice you have changed branches since you last logged in. To provide you with the correct session for your branch, you will automatically be logged out of this session. Once logged out, please ‘Sign Out’ from your Thin Client device and restart the log in process”
#GenerateForm $message
Write-Log -Msg "The correct VM has been found. "
Write-Log -Msg $LogSeparator
Write-Log -Msg ‘Logon Script Completed…’

If ($Global:Debug -ne “True”) {

shutdown -l -f
Exit}
}
Else {

Write-Log -Msg ("The script could not find a subnet for the IP address " + $CitrixThinClientIP + " in the mappings file. ")}
#Failsafe}



}
}




function ConfirmCorrectVM { param([string]$Prefix,[string]$ThinClientIP)

#
# DESCRIPTION
# Determines whether the user has connected to an approved VM for that Branch.
# Imports the local mapping file and finds the corresponding Prefix/IP Subnet combination that matches the VM Branch Prefix
# Calls the SubnetMask function to calculate whether the Thin Client IP Address is within the corresponding Subnet Range
# If the Thin Client IP Address is not within the approved subnet range for that branch. We remove the user from the VDI Group and
# return a non success, instructing the Gather-Information function to search for the correct VM
#

Import-csv $Global:LocalMappingFile |


Foreach-Object {


If ($.BranchPrefix -eq $Prefix) {

Write-Log -Msg (“Found a branch prefix matching " + $Prefix + " in the local mapping file. Attempting to compare the subnet values”)
Write-Log -Msg ("The subnet mask found for the branch prefix " + $Prefix + " is " + $
.SubnetMask)

$FoundItems = “True”

If (($CorrectMaskforIP = SubnetMask -SubnetMask $.SubnetMask -IPAddress $ThinClientIP) -eq “True”) {

Write-Log -Msg “The User is logging onto the correct machine”

return “True”
}

Else {

Write-Log -Msg (“The user is not logging onto the correct VM.”)


<# #Attempt to remove the user from the Front Office Group
Write-Log -Msg ("Removing the user from the " + $
.FrontOfficeGroup)


If((AddRemoveUser-Group -action “Remove” -GroupName $.FrontOfficeGroup) -eq “Success”) {

Write-Log -Msg ("The user has successfully been removed from the group " + $
.FrontOfficeGroup)
}

Else {

Write-Log -Msg ("Unable to remove the user from the group " + $.FrontOfficeGroup + “. Loading failsafe”)}
#Failsafe}




#Attempt to remove the user from the Back Office Group
Write-Log -Msg ("Removing the user from the " + $
.BackOfficeGroup)


If((AddRemoveUser-Group -action “Remove” -GroupName $.BackOfficeGroup) -eq “Success”) {

Write-Log -Msg ("The user has successfully been removed from the group " + $
.BackOfficeGroup)
return “False”
}

Else {

Write-Log -Msg (“Unable to remove the user from the group " + $.BackOfficeGroup + “. Loading failsafe”)}
#Failsafe}


} #>
}
}


# If we get to this point a match has not been found. Load the failsafe

If ($FoundItems -ne “True”) {

Write-Log -Msg (“Unable to find a prefix match in the mappings file for " + $prefix + “.”)}

#Failsafe }


} #End Function


function SubnetMask ($SubnetMask, $IPAddress) {

#
# DESCRIPTION
# This function accepts a subnet mask in the format of xxx.xxx.xxx.xxx/xx and the Thin Client IP address.
# The IP address range for the Subnet Mask is calculated and it is determined whether the Thin Client
# IP Address is in the IP Range.
#

#Split the $SubnetMask string to provide the Subnet ID and the CIDR
$SubnetID = ($SubnetMask.split(”/")[0])
Write-Log -Msg ("The Subnet ID extracted from the mappings file is " + $SubnetID)

$SubnetMask = (int)
Write-Log -Msg ("The CIDR extracted from the mappings file is " + $SubnetMask)

$binmask = (“1” * $SubnetMask).padright(32,[char]“0”)


#Convert the Mask to Dotted Decimal
$DottedDecimalMask = toDottedDecimal $binmask
Write-Log -Msg “Converting the CIDR to Decimal Dotted”
Write-Log -Msg ("The Decimal Dotted mask is " + $DottedDecimalMask)

#Convert the Subnet ID and the Mask to Binary
$ipBinary = toBinary $SubnetID
$smBinary = toBinary $DottedDecimalMask

#Calculate how many bits are the network ID
$netBits=$smBinary.indexOf(“0”)

#validate the subnet mask
if(($smBinary.length -ne 32) -or ($smBinary.substring($netBits).contains(“1”) -eq $true)) {

Write-Log -Msg “The subnet is Invalid”}

#validate that the IP address
if(($ipBinary.length -ne 32) -or ($ipBinary.substring($netBits) -eq “00000000”) -or ($ipBinary.substring($netBits) -eq “11111111”)) {

$ipbinary.length
$ipBinary.substring($netBits)

Write-Log -Msg “IP Address is invalid!”}

#identify subnet boundaries and convert to Dotted Decimal values

$firstAddress = toDottedDecimal $($ipBinary.substring(0,$netBits).padright(31,“0”) + “1”)
$lastAddress = toDottedDecimal $($ipBinary.substring(0,$netBits).padright(31,“1”) + “0”)
$networkID = toDottedDecimal $($ipBinary.substring(0,$netBits).padright(32,“0”))


write-log -Msg ("The first IP address in the range is : " + $firstaddress)
write-log -Msg ("The last IP address in the range is : " + $lastaddress)


#Calculate if the Thin Client IP address is within the network range

If((IsIpAddressInRange -ipAddress $IPAddress -fromAddress $firstAddress -toAddress $lastAddress) -eq “True”) {

Write-Log -Msg (“Found a Subnet (” + $networkID + ") for the IP Address " + $IPAddress)

#The IP addresses match so we can continue
$CorrectMaskforIP = “True”
return $CorrectMaskforIP}

Else {

$CorrectMaskforIP = “False”
return $CorrectMaskforIP}

} #End Function



function IsIpAddressInRange {

#
# DESCRIPTION
# Calculates whether a given IP address is within a specified IP address range
#


param(
[string] $ipAddress,
[string] $fromAddress,
[string] $toAddress
)


$ip = [system.net.ipaddress]::Parse($ipAddress).GetAddressBytes()

[array]::Reverse($ip)
$ip = [system.BitConverter]::ToUInt32($ip, 0)


$from = [system.net.ipaddress]::Parse($fromAddress).GetAddressBytes()

[array]::Reverse($from)
$from = [system.BitConverter]::ToUInt32($from, 0)


$to = [system.net.ipaddress]::Parse($toAddress).GetAddressBytes()

[array]::Reverse($to)
$to = [system.BitConverter]::ToUInt32($to, 0)


$from -le $ip -and $ip -le $to
}


<#function AddRemoveUser-Group($Action, $GroupName) {

#
# DESCRIPTION
# Adds/Removes the currently logged on user to/from the specific Active Directory Security Group
# Specify the -Action “Add” or “Remove” and the AD Group Name as parameters
#

$error.clear()


#Determine username for currently logged on user
$username = [Environment]::Username
Write-Log -Msg ("The username is " + $username)

#Set the AD Search Filter
$strFilter = “(&(objectClass=User)(samaccountname=” + $username + “))”

$objDomain = New-Object System.DirectoryServices.DirectoryEntry

#Set Search Attributes
$objSearcher = New-Object System.DirectoryServices.DirectorySearcher
$objSearcher.SearchRoot = $objDomain
$objSearcher.PageSize = 1000
$objSearcher.Filter = $strFilter
$objSearcher.SearchScope = “Subtree”

#Set Property List - Name and AD distinguished path
$colProplist = “name”,“adspath”

foreach ($i in $colPropList){$objSearcher.PropertiesToLoad.Add($i)}

$colResults = $objSearcher.FindAll()

foreach ($objResult in $colResults)

{$objItem = $objResult.Properties;

$user = $objItem.adspath}

Write-log -Msg (“Found user " + $user)

$root = [adsi]“”
$rootdn = $root.distinguishedName

Write-Log -Msg (“The Root DN is " + $rootDN)

# Bind to the Group object
$group = [adsi](“LDAP://cn=” + $GroupName + “,” + $Global:ADGroupOU + “,” +$rootdn)

#Determine whether we need to add or remove the user from the group

If ($action -eq “Add”) {

$group.add(”” + $user)
$group.SetInfo()



#Check for error. If not Podium Group, we load the failsafe
If($error[0] -and $GroupName -ne $Global:PodiumGroup) {

Write-Log -Msg ("Unable to " + $action + " the user " + $user + " to the Group " + $GroupName)
Write-Log -Msg ("The error returned is " + $error[0])}
#Failsafe}

#If we are adding to Podium Group, we cannot load failsafe again, so just return failed function
ElseIf ($error[0] -and $GroupName -eq $Global:PodiumGroup) {

If ($error[0] -match “The object already exists”) {

Write-Log -Msg “The user is already a member of the podium group”
return “Success”
}
Else {

Write-Log -Msg ("Unable to " + $action + " the user " + $user + " to the Group " + $GroupName)
Write-Log -Msg (“The error returned is " + $error[0])
return “Failed”}

}

#No errors, return Success
Write-log -Msg (“User has been added to the group " + $GroupName)
return “Success”
}


ElseIf ($action -eq “Remove”) {

$group.remove(”” + $user)
$group.SetInfo()


#Check for error. If not Podium Group, we load the failsafe
If($error[0] -and $GroupName -ne $Global:PodiumGroup){

Write-Log -Msg ("Unable to " + $action + " the user " + $user + " from the Group " + $GroupName)
Write-Log -Msg ("The error returned is " + $error[0])}
#Failsafe}

#If we are in Failsafe mode, return failed
ElseIf ($error[0] -and $GroupName -eq $Global:PodiumGroup) {

Write-Log -Msg ("Unable to " + $action + " the user " + $user + " from the Group " + $GroupName)
Write-Log -Msg ("The error returned is " + $error[0])
return “Failed”
}

#No errors, return Success
Write-log -Msg ("User has been removed from the group " + $GroupName)
return “Success”

}


} #End Function
#>

function FindCorrectVM($ThinClientIP) {

#
# DESCRIPTION
# Method for finding the Subnet and corresponding group name for a given Thin Client IP Address
#


Import-csv $Global:LocalMappingFile |

Foreach-Object {

#Call SubnetMask function to check if ThinClientIP is in Subnet Range
If ((SubnetMask $
.SubnetMask $ThinClientIP) -eq “True”) {


#If in range, TAKE THE CORRESPONDING VALUES FROM BRANCHPRINTERPREFIX AND BRANCHPRINTER ZONE AND SET THEM AS ENV VARIABLES
{SetEnvironmentVariable(”$.BranchPrinterSettings"),"$($.BranchPrinterPrefix)$($.BranchPrinterZone)",“Process”}

Write-Log -Msg (“Created Environment Variable” + $
.BranchPrinterSettings)


# DW 31/12/12 NEED TO SET AN ENVIRONMENT VARIABLE FLAG IF NO MATCH FOUND - PRESUME IT’S PROCESS LEVEL

Else {

Write-Log -Msg (“No match found create environment variable flag NoMatch”)
SetEnvironmentVariable (“NoMatch”, “NoMatch.”, “Process”)}



#Now attempt to add the user to the Back Office Group
#If{SetEnvironmentVariable("$.BranchPrinterSettings"),"$($.BranchPrinterPrefix)$($.BranchPrinterZone)",“Process”} -eq “Success”){

#FindCorrectVM Success?
Write-Log -Msg (“Successfully added environment variable”)
$FoundSubnet = “Success”
return $FindCorrectVM = “Success”
Break}

Else {

#If unsuccessful, log error
Write-Log -Msg (“Unable to add environment variable”)}
#Failsafe}

}


}

#If we reach the end of the file without a Subnet Match, return failed.
If ($FoundSubnet -ne “Success”) {

Write-Log -Msg (“Unable to find a matching subnet for the IP address " + $ThinClientIP)
$FindCorrectVM = “Failed”
return $FindCorrectVM}


} #End Function


function toBinary ($dottedDecimal){

#
# DESCRIPTION
# Covert Dotted Decimal IP address into Binary Value
#

$dottedDecimal.split(”.") | %{$binary=$binary + $([convert]::toString($
,2).padleft(8,“0”))}
return $binary

} #End Function

function toDottedDecimal ($binary){

#
# DESCRIPTION
# Covert Binary IP address into Dotted Decimal
#

do {$dottedDecimal += “.” + [string]$([convert]::toInt32($binary.substring($i,8),2)); $i+=8 } while ($i -le 24)
return $dottedDecimal.substring(1)

} #End Function


<#function GenerateForm($Message){

#
# DESCRIPTION
# Generate the message that is displayed to the user based on the VM validation
#


#region Import the Assemblies
[reflection.assembly]::loadwithpartialname(“System.Windows.Forms”) | Out-Null
[reflection.assembly]::loadwithpartialname(“System.Drawing”) | Out-Null


#region Generated Form Objects
$form1 = New-Object System.Windows.Forms.Form
$button1 = New-Object System.Windows.Forms.Button
$richTextBox1 = New-Object System.Windows.Forms.RichTextBox
$InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState



$OnLoadForm_StateCorrection=
{

#Correct the initial state of the form to prevent the .Net maximized form issue
$form1.WindowState = $InitialFormWindowState
}


$form1.AutoScaleMode = 0
$form1.AutoScroll = $True
$form1.BackColor = [System.Drawing.Color]::FromArgb(255,255,255,255)
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 541
$System_Drawing_Size.Width = 678
$form1.ClientSize = $System_Drawing_Size
$form1.ControlBox = $False
$form1.DataBindings.DefaultDataSourceUpdateMode = 0
$form1.ForeColor = [System.Drawing.Color]::FromArgb(255,255,255,255)
$form1.FormBorderStyle = 0
$form1.MinimizeBox = $False
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 541
$System_Drawing_Size.Width = 678
$form1.MinimumSize = $System_Drawing_Size
$form1.Name = “form1”
$form1.SizeGripStyle = 2
$form1.StartPosition = 3
$form1.Text = “IMPORTANT MESSAGE”
$form1.TopMost = $True
$form1.WindowState = 2
$form1.add_Load($handler_form1_Load)

$button1.Anchor = 0

$button1.DataBindings.DefaultDataSourceUpdateMode = 0
$button1.DialogResult = 1
$button1.FormBorderStyle = 0
$button1.Font = New-Object System.Drawing.Font(“Microsoft Sans Serif”,9,0,3,0)
$button1.ForeColor = [System.Drawing.Color]::FromArgb(255,0,0,0)
$button1.BackColor = [System.Drawing.Color]::FromArgb(255,192,192,192)

$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 63
$System_Drawing_Point.Y = 305
$button1.Location = $System_Drawing_Point
$button1.Name = “button1”
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 23
$System_Drawing_Size.Width = 548
$button1.Size = $System_Drawing_Size
$button1.TabIndex = 2
$button1.Text = “OK”
$button1.UseVisualStyleBackColor = $True
$button1.add_Click($button1_OnClick)

$form1.Controls.Add($button1)

$richTextBox1.Anchor = 0
$richTextBox1.BorderStyle = 0
$richTextBox1.DataBindings.DefaultDataSourceUpdateMode = 0
$richTextBox1.Font = New-Object System.Drawing.Font(“Microsoft Sans Serif”,12,1,3,0)
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 68
$System_Drawing_Point.Y = 142
$richTextBox1.Location = $System_Drawing_Point
$richTextBox1.Name = “richTextBox1”
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 122
$System_Drawing_Size.Width = 548
$richTextBox1.Size = $System_Drawing_Size
$richTextBox1.TabIndex = 1
$richTextBox1.ReadOnly = $True
$richTextBox1.Text = $message
$richTextBox1.add_TextChanged($handler_richTextBox1_TextChanged)

$form1.Controls.Add($richTextBox1)



#Save the initial state of the form
$InitialFormWindowState = $form1.WindowState

#Init the OnLoad event to correct the initial state of the form
$form1.add_Load($OnLoadForm_StateCorrection)

#Show the Form
$form1.ShowDialog()| Out-Null

} #End Function #>




#
*****************************************************************
# Main Script
#*******************************************************************

#If Debugging is enabled, initialise the log file

If ($Global:Debug -eq “True”) {

Initialise-LogFile -File $LogFile
Write-Log -Msg $LogSeparator
Write-Log -Msg ‘Logon Script Started…’

}

#Build the Mapping File directory paths

$Global:LocalMappingFile = $Global:LocalMappingFileDirectory + "&quot; + $Global:MappingFileName
$Global:CentralMappingFileDirectory = Get-ScriptDirectory



#Perform machine validation checks
#Validate-Machine

#Validate the mapping file
MappingFile

#Gather Client Information and perform VM Validation
Gather-Information


#Write log footer
Write-Log -Msg $LogSeparator
Write-Log -Msg ‘Logon Script Completed…’



#End of Script