函数参数总是为空?为什么?

时间:2015-05-30 13:25:53

标签: function powershell

有人可以告诉我,为什么这个函数调用不起作用以及为什么参数总是空的?

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'

如果用户或用户组存在,请尝试获取信息..

祝你好运

2 个答案:

答案 0 :(得分:5)

也许使用param块作为参数。

  

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

更新:如果您不使用$input作为参数名称,问题似乎已得到修复,拥有正确的变量名称可能不是一件坏事;)

此外,Powershell没有return关键字,您只需将对象作为语句推送,这将由函数返回:

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'

答案 1 :(得分:5)

$ input是自动变量。

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.