2012-03-01 97 views
0

如何返回本机中的对象?一直在看它,没有清晰,简单的例子!Powershell返回对象非cmdlet

[编辑]固定!刚刚解决它在我自己的,正确的代码是在下面!

function search-member() 
{ 
$objOU_1 = New-Object System.DirectoryServices.DirectoryEntry("LDAP://dc=somedomain") 

$objSearcher = New-Object System.DirectoryServices.DirectorySearcher 

$objSearcher.SearchRoot = $objOU_1 
$objSearcher.PageSize = 1000 
$strFilter = "(&(objectCategory=User)(sAMAccountName=username))" 
$objSearcher.Filter = $strFilter 
$objSearcher.SearchScope = "Subtree" 

$results = $objSearcher.FindAll() 

# return $results # instead of this 

$results # you first "write" what you want returned 
return # then return 
} 

$obj1 = search-member-2003 # if you take away the "$obj = " it will spit out the write which u have in the function directly. 

$obj1 # here is the boject 
+0

刚回答我自己的问题。 你必须在函数中回显(写入)你想要返回的内容,因为它将被保存在变量$ obj1中,那么你可以做它你想要的。 – 2012-03-01 10:43:47

回答

0
,如果你在你的脚本改变

这样的:

foreach ($result in $results) 
{  
    $result   
} 

或只是

return $results 

然后

$obj1 = search-member 
$obj1.gettype() 

会给'SearchResult'这一个object[]如果'用户名'包含像史密斯*这样的通配符并且存在少于两个条目(如'smith'和'smithson')。然后

$obj1[0].gettype()'SearchResult'

如果 '用户名' 是唯一$obj1类型为 'SearchResult' 的。