函数参数总是为空?

Kei*_*ung 4 powershell function

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

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'
Run Code Online (Sandbox Code Playgroud)

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

最好的祝福

Vin*_*met 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'
Run Code Online (Sandbox Code Playgroud)

  • 我认为`$ input`是你不应该使用的系统变量,更新样本 (4认同)
  • 实际上PowerShell**确实有一个`return`关键字,在某些情况下使用它非常方便:https://technet.microsoft.com/en-us/library/hh847760%28v=wps.620%29. ASPX (3认同)