我想在PowerShell中创建一个具有属性的自定义对象,然后将该对象传递给一个函数.我找到了创建自定义对象的在线示例,但它使用了HashTable.但是,我有单个对象的属性,而不是一个对象数组.
以下是我的代码示例:
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)
从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)