gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 01:03:05 24 4
gpt4 key购买 nike

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

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

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

最佳答案

在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

关于powershell - 将自定义对象传递到另一个ps1脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53081788/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com