假设我有以下PS脚本 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"
我从另一个PS脚本打电话
$ [path]\myscript.ps1 -ID 001
$ [path]\myscript.ps1 -ID 002
$ [path]\myscript.ps1 -ID 003
现在我跑完最后一个电话:
$ [path]\myscript.ps1 -ID 003
我想在之后触发一些自定义行为/步骤:
Write-Host "Step 2 $ID"
myscript.ps1 中的。我考虑过这个:
$ [path]\myscript.ps1 -ID 001
$ [path]\myscript.ps1 -ID 002
$ [path]\myscript.ps1 -ID 003 -customScript "[path]\custom.ps1"
然后将 myscript.ps1 更新为:
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"
也许还有一些更优雅的方式呢?
我看过: http://blogs.msdn.com/b/powershell/archive/2008/06/11/powershell-eventing-quickstart.aspx
但它似乎并不符合目的。
答案 0 :(得分:4)
您可以传递自定义ScriptBlock并执行它:
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"
示例:
$ [path]\myscript.ps1 -ID 001
$ [path]\myscript.ps1 -ID 002
$ [path]\myscript.ps1 -ID 003 -custom {Write-Host "I'm a custom scriptblock!"}
有关执行scriptblocks的更多信息: