简体   繁体   中英

passing custom object to another ps1 script

I'd like to pass a custom made object from script to another.

Beginning of subscript.ps1 there are input parameters:

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

In the main.ps1 I'm trying to call the subscript.ps1 after introducing a custom object:

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

When calling like this if i check in subscript $custClassData.GetType it returns System.String, so i only get the name of the object there. If I generate class and object in the powershell manually and put data there and pass it to the subscript the type is custClass.

In subscript.ps1 the $custClassData parameter needs to validate the type [CustClass] not [object] . So something like:

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

This way the data that is passed to that parameter must be of the type [CustClass] .

Additionally, the way you are calling subscript.ps1 does not look correct. You do not need to call powershell.exe in order to invoke subscript.ps1 . powershell.exe will always throw an error here.

You should change subscript.ps1 to subscript.psm1 , and turn the contents of the script into a function, and use it like this:

In subscript.psm1 :

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

In 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

Calling powershell.exe casts everything to strings. Launch the script file directly instead:

File: sub.ps1

param(
  [object]$foo
)

$foo

File: main.ps1

class myClass{
    [string]$A
}

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

.\sub.ps1 $myObject

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM