简体   繁体   中英

Get-ADUser Powershell Parameter

I want to write a little Tool like a little CLI where I can get Informations out of our AD-Domain. I have that function (listed below) which works but I want it not to ask me the Parameter in the second place. The Goal is to let the Tool run in a Loop where I can type the Function-Shortcuts with given Parameter like "Username"

ListUserInformation -Username "Firstname, Lastname" (Something like that.) I tryed double and single quotes but it keeps asking in the next line about a Username. Can some1 help me with that? Here is the Function:

    function ListUserInformation {
        [CmdletBinding()]
    param (
    [Parameter(Mandatory=$true)][String]$Username
    )
        
        $target = $Username
        $x = Get-ADUser -Filter "CN -like '$target'"  -SearchBase $SearchBase -Properties CN,Title,SamAccountName,emailaddress,officephone | Out-String
            Select-Object CN,Title,SamAccountName,emailaddress,officephone
        write-host $x }

As commented, remove Out-String . Also, your function could be more versatile if you add a second (optional) parameter $SearchBase .

Write-Host just outputs to console and is not a return value of the function. Either use the return keyword or leave it out alltogether.

Something like this:

function ListUserInformation {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true, Position = 0)]
        [String]$Username,

        [Parameter(Mandatory = $false)]
        [String]$SearchBase = 'CN=SomeWhere,CN=Users,DC=Company,DC=com'  # insert your predefined OU searchbase here
    )
    $Properties = 'CN','Title','SamAccountName','EmailAddress','OfficePhone'
    if ([string]::IsNullOrWhiteSpace($SearchBase)) {
        Get-ADUser -Filter "CN -like '$Username'" -Properties $Properties |
        Select-Object $Properties
    }
    else {
        Get-ADUser -Filter "CN -like '$Username'" -SearchBase $SearchBase -Properties $Properties |
        Select-Object $Properties
    }
}

Usage:

$x = ListUserInformation -Username 'Pa1n4ndt3rr0r'

You only need to change one minor thing. Write-Host doesn't give you an output that you can use in follow up commands.

Return on the other hands does.

function ListUserInformation {
    [CmdletBinding()]
param (
[Parameter(Mandatory=$true)][String]$Username
)
    
    $target = $Username
    $x = Get-ADUser -Filter "CN -like '$target'"  -SearchBase $SearchBase -Properties CN,Title,SamAccountName,emailaddress,officephone | Out-String
        Select-Object CN,Title,SamAccountName,emailaddress,officephone
return $x }

That should solve your problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM