2

How would one go about returning an object from powershell into another powershell script? I am looking to automate some of my deployments using powerhsell so that we can have easier to repeat deployments with a minimum amount of human intervention.

The idea would be to have a "library" of scripts for the various processes that occur during a deployment that take a series of arguments, and then have a main deployment script that just calls each of those subscripts with arguments for the files being used. For example, for one deployment, I might have to create A login on a Sql Server, add some functions or stored procedures to a database , Deploy SSRS Reports, update the shared data sources for the SSRS to use an AD Service account, etc.

I am able to cram everything into a single script with a bunch of functions, but for easier re-usability, I would like to take each basic task - (Run SQL Scripts, get a credential from Secret Server , run a folder of SQL Scripts, Deploy SSRS Reports , etc. ) and place it in its own script with parameters that can be called from my main script. This would allow me to have a main script that just calls each task script with parameters. In order to do this though, for things like updating the AD Credentials, I would need a way to return the PScredential object that the function currently returns from a separate script instead.

1 Answer 1

4

You can explicitly return an object by using the return keyword:

return $myObject

Or you can implicitly return the object by explicitly using Write-Ouptut or implicitly outputting the object by having it bare on a line:

Write-Output $myObject

Or

$myObject
Sign up to request clarification or add additional context in comments.

4 Comments

Using return can interrupt function flow (especially when involving the pipeline) and as such isn't viewed as a best practice among the PS community.
@TheIncorrigible1 Do you have a link to a MS source for that. I understand that it sometimes gets used incorrectly and thus causes problems for people that don't understand what it does, but incorrectly using a command is pretty much against best practice all the time in every language.
I'm not aware of a Microsoft best-practices list but there is a community one on GitHub that has many MSFT contributors.
Beware, though, that returning objects normally does not work across process boundaries, i.e. if you run the script in a different PowerShell process (e.g. powershell.exe -File script.ps1) the output would not be returned as an object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.