I've got a script that asks for a Username
and DateRemove (MM/DD/YYYY)
. This input is exported to a config.CSV
file with the -Append
function and the CSV
format is Username,DateAdd,DateRemove
.
I'm wanting to create a second PS file to run as a daily scheduled task. This is where I'm lost and hoping for help...
I'd like to reference this config.CSV
and compare the DateRemove
to the current date, if there's a match I want to take the Username
and execute "Remove-ADGroupMember -Identity GroupName -Members $User
", if there's no match I want it to do nothing.
Tried a single PS script creating a "removal" job but this failed and used variables as arguments in my scheduled task. Not to mention it was going to create 100s of task scheduler jobs. Which has led me to one PS file for user input and one file for scheduled job referencing a "source" file.
$User = Read-Host -Prompt 'Enter the username you want to add to group'
if ($User) {
Write-Host "$User will be added to the group"
} else {
Write-Warning -Message "We need a username to run this script"
}
Add-ADGroupMember -Identity Group -Members $User
$Date = Read-Host -Prompt 'Enter removal date'
if ($Date) {
Write-Host "$User will be removed from group on $Date"
} else {
Write-Warning -Message "We need a date to run this script"
}
[PSCustomObject]@{
Username = $User
DateAdd = Get-Date -Format g
DateRemove = $Date
} | Export-Csv -Path C:\config.csv -Append -NoTypeInformation -Encoding ASCII
$Date = Get-Date
$Config = Import-Csv C:\config.csv
Foreach($DateRemove in $Config) {
$DateRemove = $DateRemove.Date
if "$DateRemove" -eq $Date
Now I'm just confused..
I assume you're looking for something like the following:
$today = [datetime]::Today
Import-Csv C:\config.csv | ForEach-Object {
if ([datetime] $_.DateRemove -eq $today) {
Remove-ADGroupMember -Identity $group -Members $_.Username
}
}
Note that group information isn't part of the CSV you create in your question, so I'm assuming that it is stored in variable $group
here.
[datetime]::Today
returns today's date at midnight (the start of the day), i.e., without a time-of-day componentThanks, LotPings. and, given that the date read from the CSV file ([datetime] $_.DateRemove
) won't have one either, the -eq
comparison works as intended.
Generally, avoid comparing string representations of time stamps ("$DateRemove"
), due to variations in formatting and lack of precision.