如何使用 Powershell 创建函数

How to create a Function using Powershell

我需要有关以下代码的帮助。我希望脚本执行以下操作:提示用户输入 AD 组名,如果找到组名,则将组成员导出到 CSV 文件。其中一个要求是我必须包含一个函数语句。先感谢您。

如果我使用类似于以下示例的变量,代码将起作用:$groupsusers = Get-ADGroup -Identity $nameofgroup,而不是函数语句。 但是,我不想使用变量,我想实现一个函数语句。

$prompt = "Enter A Group Name"
do
{
$nameofgroup = Read-Host $prompt
}
until(!$(dsquery Group-Object $nameofgroup; $prompt = "Group 
'$nameofgroup' was not found, try again"))

$nameofgroup = Read-Host $prompt

function GetGroupInfoToCsv (#what parameters go here?){

ForEach-Object{

$settings = @{ Group = $_.DistinguishedName; Member = $null }
$_| Get-ADGroupMember |
ForEach-Object{
    $settings.Member = $_.DistinguishedName
    New-Object PsObject -Property $settings
}

}

}

GetGroupInfoToCsv | Export-Csv .\GroupMembers.csv -NoTypeInformation

您可以将请求用户输入和返回信息合并到同一个函数中。像这样:

function Get-GroupMembers {
    $prompt = "Enter A Group Name. Press Q to quit"
    # create an endless loop
    while ($true) {
        Clear-Host
        $answer = Read-Host $prompt
        # if the user has had enough, exit the function
        if ($answer -eq 'Q') { return }

        # try and find one or more AD groups using the answer as (part of) the name
        $group = Get-ADGroup -Filter "Name -like '*$answer*'"
        # if we have found something, exit the while loop and start enumerating the members
        if ($group) { break }

        $prompt = "Group '$answer' was not found, try again. Press Q to quit"
    }

    # you only get here if Get-ADGroup found one or more groups
    $group | ForEach-Object {
        # output a PSObject with the properties you are after
        $members = $_ | Get-ADGroupMember
        foreach ($member in $members) {
            [PsCustomObject]@{
                'Group'  = $_.DistinguishedName
                'Member' = $member.DistinguishedName
            }
        }
    }
}

# call the function
$groupinfo = Get-GroupMembers
# test if the function returned anything. 
# the user could have cancelled of the group had no members to output
if ($groupinfo) {
    Write-Host "Adding $($groupinfo.Count) items to the CSV file"
    # without -Append, you would overwrite your CSV file..
    $groupinfo | Export-Csv .\GroupMembers.csv -NoTypeInformation -Append
}
else {
    Write-Host 'Nothing found..'
}

如您所见,我更改了函数名称,使其符合 PowerShell 中的 Verb-Noun 约定。