将自定义对象传递到另一个ps1脚本

时间:2018-10-31 10:59:19

标签: powershell

我想将自定义对象从脚本传递给另一个。

subscript.ps1的开头有输入参数:

param(
  [string]$someString,
  [object]$custClassData
 )

在main.ps1中,我尝试在引入自定义对象后调用subscript.ps1:

class custClass{
   [string]$string1
   [string]$string2
   [string]$string3
}

$customizedObject = [custClass]::new()
$customizedObject.string1 = "smthng1"
$customizedObject.string2 = "smthng2"
$customizedObject.string3 = "smthng3"
$scriptPath = ".\subscript.ps1"
$smString = "somethingsomething"
powershell.exe -file $scriptPath -someString $smString -custClassData $customizedObject

当像这样调用时,如果我签入下标$ custClassData.GetType,它将返回System.String,所以我只在那里获得对象的名称。如果我在Powershell中手动生成类和对象,然后将数据放入其中,然后将其传递给下标,则类型为custClass。

2 个答案:

答案 0 :(得分:1)

subscript.ps1 中,$custClassData参数需要验证类型[CustClass]而不是[object]。像这样:

param(
  [string]$someString,
  [CustClass]$custClassData
 )

这样,传递给该参数的数据必须为[CustClass]类型。

此外,您调用 subscript.ps1 的方式看起来不正确。您无需调用powershell.exe即可调用 subscript.ps1 powershell.exe总是在这里抛出错误。

您应该将 subscript.ps1 更改为 subscript.psm1 ,然后将脚本的内容转换为函数,然后像这样使用它:

在subscript.psm1 中:

function Do-TheNeedful {
    param(
      [string]$someString,
      [CustClass]$custClassData
    )
    #~
    # do work
    #~
}

在main.ps1

class custClass{
   [string]$string1
   [string]$string2
   [string]$string3
}

Import-Module subscript.psm1

$customizedObject = [custClass]::new()
$customizedObject.string1 = "smthng1"
$customizedObject.string2 = "smthng2"
$customizedObject.string3 = "smthng3"
Do-TheNeedful -someString "a_string" -custClassData $customizedObject

答案 1 :(得分:1)

调用powershell.exe会将所有内容转换为字符串。而是直接启动脚本文件:

文件:sub.ps1

param(
  [object]$foo
)

$foo

文件:main.ps1

class myClass{
    [string]$A
}

$myObject = [myClass]::new()
$myObject.A = "BAR"

.\sub.ps1 $myObject
相关问题