Keine-Ahnung
Keine-Ahnung

Reputation: 741

Function parameter always empty why?

Can someone tell me, why this function call does not work and why the argument is always empty ?

function check([string]$input){
  Write-Host $input                             #empty line
  $count = $input.Length                        #always 0
  $test = ([ADSI]::Exists('WinNT://./'+$input)) #exception (empty string) 
  return $test
}

check 'test'

Trying to get the info if an user or usergroup exists..

Best regards

Upvotes: 6

Views: 4999

Answers (2)

Andrew Semenov
Andrew Semenov

Reputation: 151

$input is an automatic variable.

https://technet.microsoft.com/ru-ru/library/hh847768.aspx

$Input

Contains an enumerator that enumerates all input that is passed to a function. The $input variable is available only to functions and script blocks (which are unnamed functions). In the Process block of a function, the $input variable enumerates the object that is currently in the pipeline. When the Process block completes, there are no objects left in the pipeline, so the $input variable enumerates an empty collection. If the function does not have a Process block, then in the End block, the $input variable enumerates the collection of all input to the function.

Upvotes: 8

Vincent De Smet
Vincent De Smet

Reputation: 4979

Perhaps use a param block for parameters.

https://technet.microsoft.com/en-us/magazine/jj554301.aspx

Update: the problem seems to be fixed if you don't use $input as a parameter name, maybe not a bad thing to have proper variable names ;)

Also Powershell doesn't have return keyword, you just push the object as a statement by itself, this will be returned by function:

function Get-ADObjectExists
{
  param(
    [Parameter(Mandatory=$true, ValueFromPipeline=$true)]
    [string]
    $ObjectName
  )
  #return result by just calling the object (no return statement in powershell)
  ([ADSI]::Exists('WinNT://./'+$ObjectName)) 
}

Get-ADObjectExists -ObjectName'test'

Upvotes: 6

Related Questions