如何从另一个命令引用属性



所以我试图设置一个解锁用户帐户的脚本。

现在这就是我所拥有的:

function unlocktm
{
$user = read-host "Who is the user?"
Unlock-ADAccount -Identity $user -Credential adminaccount
Write-host "Account for $user has been unlocked!"
}

现在是困难的部分,我们的用户用户名是基于他们的电子邮件。我们像去年一样切换了电子邮件格式。所以有些人的电子邮件jdoe@company.com其他的john.doe@company.com

所以当我现在的剧本问";用户是谁"我必须输入并知道用户的用户名样式(first.lastname或flastname(。有1500名用户,我不太清楚每一封电子邮件。

所以我想做的是让它在要求";这个用户是谁"我只需要输入John Doe,它将运行我设置的第二个脚本,该脚本可以在AD中搜索该用户,提取属性并将其应用到第一个脚本中。让我解释得更好。目前我有第二个脚本,它是:

function findtm
{
$Firstname = Read-Host "What is the users Firstname?"
$Lastname = Read-Host "What is the Users Lastname?"
Get-ADUser -Filter "Surname -like '$Lastname*' -and GivenName -like '$Firstname*'"
}

然后提取该用户的信息并向我显示他们的电子邮件风格;samaccountname";。

所以最终,我需要它做的是:

我运行函数,它会询问我的用户。

我可以输入";John Doe";

然后它将在后台运行第二个脚本;John Doe";然后如果它发现了一个无名氏;samaccountname";属性(john.doe或jdoe(,将其附加到答案以代替";john doe"然后脚本为johndoe运行unlockad命令并解锁他的帐户。

我可能在很大程度上高估了这一点,但我在想"如果其他人也能做到,但我不知道如何设置它来实现";samaccountname";所有物

在我看来,您应该将函数视为独立的单元,将它们所需的信息作为参数。我通常会把提示或用户交互留给最外层。

假设Get-ADUser返回一个对象,该对象也可以与Unlock-ADAccount一起使用。

function unlocktm
{
param($Identity)
Unlock-ADAccount -Identity $Identity -Credential adminaccount
Write-host "Account for $($Identity.SamAccountName) has been unlocked!"
}
function findtm
{
param($Firstname, $Lastname)
Get-ADUser -Filter "Surname -like '$Lastname*' -and GivenName -like '$Firstname*'"
}
# the outer script area
$Firstname = Read-Host "What is the users Firstname?"
$Lastname = Read-Host "What is the Users Lastname?"
$Id = findtm -Firstname $Firstname -Lastname $Lastname
unlocktm -Identity $id

现在,如果你想让它更花哨一点:

function unlocktm
{
[CmdletBinding()]
param(
[Parameter(ValueFromPipeline=$true)]
$Identity
)
Process {
Unlock-ADAccount -Identity $Identity -Credential adminaccount
Write-host "Account for $($Identity.SamAccountName) has been unlocked!"
}
}
function findtm
{
param($Firstname, $Lastname)
Get-ADUser -Filter "Surname -like '$Lastname*' -and GivenName -like '$Firstname*'"
# by simply calling this, the value returned becomes the return value of your function
}
# the outer script area
$Firstname = Read-Host "What is the users Firstname?"
$Lastname = Read-Host "What is the Users Lastname?"
findtm -Firstname $Firstname -Lastname $Lastname | unlocktm

有很多可能性,但也许这是一个好的开始?

最新更新