Check for a switch with PowerShell script
Uses switches with your PowerShell scripts
January 29, 2017
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.
<#.SYNOPSISEnables a user for a VLAN for a specific location.DESCRIPTIONEnables a user for a VLAN for a specific location.PARAMETER UsernameUser name.PARAMETER VLANUser vlan.PARAMETER LocationUser location.PARAMETER RemoveMemberUser RemoveMember.EXAMPLEEnableVLANUser 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 = $falseif ($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
About the Author
You May Also Like