Q. How can I check for a switch using PowerShell?
A. I recently had to create a script that enabled a user to be specified then had to be added to two groups which represented the target location for access and a VLAN. Based on these values two group names were generated (based on a standard) then the user added to them. The groups already existed for all the possible locations and VLANs. After being passed the values a check is performed to ensure they exist. I also wanted the option to remove a user from the groups which is accomplished via a single switch RemoveMember. Then in the code you can check if the switch is passed using RemoveMember.IsPresent. Below is the full script.
<#
.SYNOPSIS
Enables a user for a VLAN for a specific location
.DESCRIPTION
Enables a user for a VLAN for a specific location
.PARAMETER Username
User name
.PARAMETER VLAN
User vlan
.PARAMETER Location
User location
.PARAMETER RemoveMember
User RemoveMember
.EXAMPLE
EnableVLANUser johnsav 99 DAL
#>
[cmdletbinding()]
Param(
[Parameter(ValuefromPipeline=$true,Mandatory=$true)][string]$username,
[Parameter(ValuefromPipeline=$true,Mandatory=$true)][string]$vlan,
[Parameter(ValuefromPipeline=$true,Mandatory=$true)][string]$loc,
[Parameter(ValuefromPipeline=$false,Mandatory=$false)][switch]$RemoveMember)
#Check if the entries are valid
$vlangroupname = "VLAN" + $vlan + "GRP"
$locgroupname = "LOC" + $loc + "VLGRP"
$userobj = Get-ADUser -LDAPFilter "(SAMAccountName=$username)"
$vlanobj = Get-ADGroup -LDAPFilter "(SAMAccountName=$vlangroupname)"
$locobj = Get-ADGroup -LDAPFilter "(SAMAccountName=$locgroupname)"
$errorFound = $false
if ($userobj -eq $null) {"User not valid";$errorFound = $true}
if ($vlanobj -eq $null) {"VLAN not valid";$errorFound = $true}
if ($locobj -eq $null) {"Location not valid";$errorFound = $true}
if(!$errorFound)
{
Write-Verbose "Looking good and adding user to groups"
if($RemoveMember.IsPresent) #if removing
{
$userobj | Remove-ADPrincipalGroupMembership -MemberOf $vlanobj -Confirm:$false
$userobj | Remove-ADPrincipalGroupMembership -MemberOf $locobj -Confirm:$false
}
else #if adding
{
$userobj | Add-ADPrincipalGroupMembership -MemberOf $vlanobj
$userobj | Add-ADPrincipalGroupMembership -MemberOf $locobj
}
}
Usage is as follows to add:
.\EnableVLANUser.ps1 johnsav 100 DAL
To remove:
.\EnableVLANUser.ps1 johnsav 100 DAL –RemoveMember