Search code examples
powershellargs

How to prompt for $args when missing


My script:

$computername=$args[0]
if ($args -eq $null) { $computername = Read-Host "enter computer name" }
Get-ADComputer -Id $computername -Properties * | select name,description

If I pass the argument with the script i.e.:

get-ComputerName.ps1 computer01

it works fine. However if I skip the computer I want it to prompt me but instead I'm getting this error:

Get-ADComputer : Cannot validate argument on parameter 'Identity'. The argument
is null. Provide a valid value for the argument, and then try running the
command again.
At U:\get-ADComputer-assigned-user.ps1:9 char:20
+ Get-ADComputer -Id $computername -Properties * | select name,description
+                    ~~~~~~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [Get-ADComputer], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.ActiveDirectory.Management.Commands.GetADComputer

I cannot figure out how to make it work.


Solution

  • Don't use the automatic variable $args, but define a specific mandatory parameter for the computername:

    [CmdletBinding()]
    Param(
      [Parameter(Mandatory=$true, Position=0)]
      [string]$ComputerName
    )
    
    Get-ADComputer -Id $ComputerName -Properties * | Select-Object Name, Description
    

    That will allow you to run your script like this:

    ./Get-ComputerName.ps1 -ComputerName computer01
    

    or like this:

    ./Get-ComputerName.ps1 computer01
    

    If the parameter is missing you'll be prompted for it:

    PS C:\> ./Get-ComputerName.ps1
    
    cmdlet test.ps1 at command pipeline position 1
    Supply values for the following parameters:
    ComputerName: _

    If you want the script to throw an error instead of prompting for a missing parameter you could do it like this:

    [CmdletBinding()]
    Param(
      [Parameter(Mandatory=$false, Position=0)]
      [string]$ComputerName = $(throw 'Parameter missing!')
    )
    
    Get-ADComputer -Id $ComputerName -Properties * | Select-Object Name, Description
    

    Check the documentation for further information about parameter handling in PowerShell.