Пустое значение Powershell Datetime - PullRequest
2 голосов
/ 31 марта 2020

Я разрабатываю PowerShell для даты истечения срока действия учетной записи пользователя AD. Но я столкнулся с проблемой, которая не может передать пустой параметр, чтобы установить дату истечения срока действия учетной записи пользователя AD на НИКОГДА.

Пожалуйста, помогите! Спасибо.

https://i.stack.imgur.com/Zt8sv.png

Вот мой сценарий ниже.

import-module C:\PS\color_menu.psm1
CreateMenu -Title "AD User Account Expire Tools" -MenuItems "View the User Account Expire Date","Set the User Account Expire Date","Exit" -TitleColor Red -LineColor Cyan -menuItemColor Yellow
do {
  [int]$userMenuChoice = 0
  while ( $userMenuChoice -lt 1 -or $userMenuChoice -gt 3) {
    Write-Host "1. View the User Account Expire Date"
    Write-Host "2. Set the User Account Expire Date"
    Write-Host "3. Exit"

    [int]$userMenuChoice = Read-Host "Please choose an option"
    switch ($userMenuChoice) {
      1{$useraccount = Read-Host -prompt "Please input an user account"
        Get-ADUser -Identity $useraccount -Properties AccountExpirationDate | Select-Object -Property SamAccountName, Name, AccountExpirationDate
       Write-Host "";
       Write-Host "";
        }
      2{$useraccount = Read-Host -prompt "Please input an user account"
        [Datetime]$expiredatetime = Read-Host -prompt "Please input the user expire date and time (DateFormat: MM/dd/yyyy)" 
        Set-ADAccountExpiration -Identity $useraccount -DateTime $expiredatetime
       Write-Host "";     
       Write-Host "";
        Get-ADUser -Identity $useraccount -Properties AccountExpirationDate | Select-Object -Property SamAccountName, Name, AccountExpirationDate
       Write-Host "";     
       Write-Host "";

       }
      3{Write-Host "Exit";Exit
       }
      default {Write-Host "Incorrect input" -ForegroundColor Red
      Write-Host "";
      Write-Host "";
      }
    }
  }
} while ( $userMenuChoice -ne 3 )```



1 Ответ

5 голосов
/ 31 марта 2020

Используйте Clear-ADAccountExpiration , чтобы установить учетную запись, для которой никогда не истекает срок действия.

Кроме того, вы не можете напрямую использовать переменную с ограничением типа [datetime] с вашим вызовом Read-Host, потому что преобразование пустая строка ('') до [datetime] не поддерживается (ошибка, которую вы видели).

Вот один из способов решения этой проблемы:

do {
  # Read the input as a string first...
  $expiredatetimeStr = Read-Host -prompt "Please input the user expiration date and time (DateFormat: MM/dd/yyyy) or just press Enter to make the account non-expiring"
  # ... and then try to convert it to [datetime]
  if ($expiredatetime = $expiredatetimeStr -as [datetime]) {
    Set-ADAccountExpiration -Identity $useraccount -DateTime $expiredatetime
  } 
  elseif ($expiredatetimeStr.Trim() -eq '') {  # empty input -> no expiration
    Clear-ADAccountExpiration -Identity $useraccount
  }
  else { # invalid input
    Write-Warning 'Please enter a valid date.'
    continue
  }
  break
} while ($true)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...