1

Assume I have the following PS Script myscript.ps1:

param(
  [string]$ID
)

Write-Host "Step 1 $ID"
Write-Host "Step 2 $ID"
# Inject some custom step here
Write-Host "Step 3 $ID"

That I call from another PS script with

$ [path]\myscript.ps1 -ID 001
$ [path]\myscript.ps1 -ID 002
$ [path]\myscript.ps1 -ID 003

Now when I run the last call:

$ [path]\myscript.ps1 -ID 003

I would like to trigger some custom behavior/steps just after:

Write-Host "Step 2 $ID"

in myscript.ps1. I considered this:

$ [path]\myscript.ps1 -ID 001
$ [path]\myscript.ps1 -ID 002
$ [path]\myscript.ps1 -ID 003 -customScript "[path]\custom.ps1"

and then update myscript.ps1 to:

param(
  [string]$ID,
  [string]$custom=""
)

Write-Host "Step 1 $ID"
Write-Host "Step 2 $ID"
if($custom) {
    & $custom
}
# Inject some custom step here
Write-Host "Step 3 $ID"

Maybe there are some more elegant way of doing this?

I have looked at: http://blogs.msdn.com/b/powershell/archive/2008/06/11/powershell-eventing-quickstart.aspx

but it does not really seem to fit the purpose.

1 Answer 1

4

You can pass custom ScriptBlock and execute it:

param(
  [string]$ID,
  [scriptblock]$custom
)

Write-Host "Step 1 $ID"
Write-Host "Step 2 $ID"

# Inject some custom step here
if($custom){. $custom}

Write-Host "Step 3 $ID"

Example:

$ [path]\myscript.ps1 -ID 001
$ [path]\myscript.ps1 -ID 002
$ [path]\myscript.ps1 -ID 003 -custom {Write-Host "I'm a custom scriptblock!"}

More about executing scriptblocks:

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

4 Comments

Whether that's more elegant than passing the path to a custom script file is debatable, though.
@AnsgarWiechers Scriptblock can run custom scipt, so it's more versatile IMO.
A custom script can run custom scriptblock as well. Both approaches are equivelent in terms of functionality.
@AnsgarWiechers Scriptblocks are easier to build on the fly then files. Saves you one intermediate step and disk I/O. Of course, it depends on a amount of code to execute - after some threshold creating a full-fledged script is more preferable. But for the short snippets I'd use a scriptblock.

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.