首页 > 解决方案 > 使用 powerShell 问题在 AD 中允许/Denny logOnHours

问题描述

我有一个 PS 脚本,由任务计划程序和 AD 中的 Allow/Denny logOnHours 为用户按开始日期运行(存储在 extensionAttribute 中)。这个问题是,并非所有需要被允许的用户都被允许(例如,从今天开始的 10 名新员工,只有 6 名被允许,所有其他人都保持拒绝状态)。

这是我的脚本:

$ErrorActionPreference = 'SilentlyContinue'

$Logfile = "c:\mypath.txt"

Function LogWrite
{
   Param ([string]$logstring)
   Add-content $Logfile -value $logstring
}

$date = Get-Date -Format "dd/MM/yyyy HH:mm"
$message = $date + ' - Running Allow/Denny script' 
LogWrite $message

Import-Module ActiveDirectory 
$currentDate = (Get-Date).Date
[dateTime]$startingDate = 0
$SearchBase = "OU=Users,DC=DC,DC=my"
$logonhoursAllow=@{"Logonhours"= [byte[]]$hours=@(255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255)}
$logonhoursDeny=@{"Logonhours"= [byte[]]$hours=@(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}

Get-ADUser -SearchBase $SearchBase -Properties extensionAttribute1 -Filter {(extensionAttribute1 -like '*')} | ForEach-Object {
    if ([datetime]::TryParseExact($_.extensionAttribute1, 'dd/MM/yyyy', $null, 'None', [ref]$startingDate)) {
        if ($startingDate -eq $currentDate) {
          $message = 'LogOnHours Enabled for: ' + $_.SamAccountName
          LogWrite $message
          Set-ADUSer -identity $_.SamAccountName -Replace $logonHoursAllow 
        }
        elseif($startingDate -gt $currentDate) {
          $message = 'LogOnHours Disabled for: ' + $_.SamAccountName
          LogWrite $message
          Set-ADUSer -identity $_.SamAccountName -Replace $logonHoursDeny
        }
    }
    else {
          $message = $($_.SamAccountName) + " has bad value in attribute and no affected from this script." 
          LogWrite $message
        
    }
}

此外,这就是我在检查 logonHours 属性时看到的内容: 在此处输入图像描述

在 TS 脚本中运行-executionpolicy bypass

任何想法?

标签: powershellactive-directory

解决方案


推荐阅读