6

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

0

2 Answers 2

9

$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.

Sign up to request clarification or add additional context in comments.

Comments

6

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'

5 Comments

I think $input is a system var you shouldn't use, updated sample
Perfect. changing input to something else and it worked. Thank you soooo much
Actually PowerShell does have a return keyword and in some scenarios its quite convenient to use it: technet.microsoft.com/en-us/library/…
@ManuelBatsching hah! beat me to it by a second :)
oh joy, so I was wrong on the param block, return keyword and even took me a while to figure out $input was an automatic variable... pretty bad... at least I learned from this too!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.