I am trying to create a PowerShell script that will be executed via a task every day. The task will check if a user has been a member of an AD group longer than 7 days. If so, that user will be removed. The data is imported from a CSV file in which we will insert the date the user was added to the group:
samaccountname,Date
user 1,20/01/2022
user2,06/02/2022
This is the code I wrote:
$users = "C:\Path to CSV\File.csv"
Import-Module ActiveDirectory
Import-Csv $users
foreach ($user in $Users)
{
$CheckDate2 = get-date ($user.'Date').AddDays(7)
$CheckDate1 = get-date ($user.'Date')
if ($CheckDate1 -lt $CheckDate2){
exit
}
else{
Remove-ADGroupMember -Identity "Group Name" -Members $user.samaccountname -Confirm:$false
}
}
This is the errors I am receiving:
You cannot call a method on a null-valued expression.
At line:8 char:1
+ $CheckDate2 = get-date ($user.'Date').AddDays(7)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
Get-Date : Cannot bind parameter 'Date' to the target. Exception setting "Date": "Cannot convert null to type "System.DateTime"."
At line:9 char:24
+ $CheckDate1 = get-date ($user.'Date')
+ ~~~~~~~~~~~~~~
+ CategoryInfo : WriteError: (:) [Get-Date], ParameterBindingException
+ FullyQualifiedErrorId : ParameterBindingFailed,Microsoft.PowerShell.Commands.GetDateCommand
Remove-ADGroupMember : Cannot validate argument on parameter 'Members'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.
At line:16 char:68
+ ... tity "Group Name" -Members $user.samaccountname -Confir ...
+ ~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Remove-ADGroupMember], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.ActiveDirectory.Management.Commands.RemoveADGroupMember