Powershell:如何创建自定义对象并将其传递给PowerShell中的功能?

LP1*_*P13 3 powershell

我想在PowerShell中创建一个具有属性的自定义对象,然后将该对象传递给一个函数.我找到了创建自定义对象的在线示例,但它使用了HashTable.但是,我有单个对象的属性,而不是一个对象数组.

  1. 如果可能的话,我想创建单个对象而不是HashTable.
  2. 如果要使用HashTables,我该如何检索对象并将其传递给函数?

以下是我的代码示例:

function CreateObject()
{       
  $properties = @{      
    'TargetServer' = “ServerName”;
    'ScriptPath' = “SomePath”;
    'ServiceName' = "ServiceName"
 }

   $obj = New-Object -TypeName PSObject -Property $properties    

   Write-Output $obj.TargetServer
   Write-Output $obj.ScriptPath
   Write-Output $obj.ServiceName

   return $obj
}

 function Function2([PSObject] $obj)
{   
   Do something here with $obj
}


$myObj = CreateObject

Function2 $myObj
Run Code Online (Sandbox Code Playgroud)

编辑1
感谢@Frode和@Matt.我不知道'return'语句也会返回其他结果.以下工作会吗?

function CreateObject()
{      
    return New-Object -TypeName PSObject -Property @{     
       'TargetServer' = "ServerName"
       'ScriptPath' = "SomePath"
       'ServiceName' = "ServiceName"
      }
}

function Init()
{
   // Do something here

   $myObject = CreateObject()

  // Do something here with $myObject

  return $myObject
}

function Funcntion2([PSObject] $obj)
{
  //Do somthing with $obj
}

$obj = Init

Function2 $obj
Run Code Online (Sandbox Code Playgroud)

Mat*_*att 7

about_return重要的是要知道

在Windows PowerShell中,即使没有包含Return关键字的语句,每个语句的结果也会作为输出返回.

因此,Frode说你将获得一个字符串数组.你想要整体回归你的对象而不是它的部分.如果函数的目的只是返回该自定义对象,那么您可以将该语句缩减为单行.

function CreateObject()
{      
    return New-Object -TypeName PSObject -Property @{     
        'TargetServer' = "ServerName"
        'ScriptPath' = "SomePath"
        'ServiceName' = "ServiceName"
    }
}
Run Code Online (Sandbox Code Playgroud)

如果你至少拥有PowerShell 3.0,那么你可以使用[pscustomobject]类型转换来完成同样的事情.

function CreateObject()
{      
    return [pscustomobject] @{     
        'TargetServer' = "ServerName"
        'ScriptPath' = "SomePath"
        'ServiceName' = "ServiceName"
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,在这两种情况下,return关键字都是可选的,但要知道它仍然可以用作函数的逻辑出口(所有输出直到该点仍然返回).

如果您不需要将函数的结果保存在变量中,您也可以将其链接到下一个函数中.

Function2 (CreateObject)
Run Code Online (Sandbox Code Playgroud)