2015-05-30 92 views
3

有人可以告訴我,爲什麼這個函數調用不起作用,爲什麼參數總是空的?函數參數總是爲空爲什麼?

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' 

試圖讓信息如果一個用戶或用戶組存在..

問候

回答

4

也許使用參數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' 
+0

沒有改變,同樣的錯誤 – marian04

+4

我想'$ input'是一個系統的無功,你不應該使用,更新的樣本 –

+0

但沒錯,PARAM塊不是強制性無論是。 –

3

$輸入是自動變量。

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.