问题
Copy and paste the following into a new Powershell ISE script and hit F5:
workflow workflow1{
"in workflow1"
func1
}
function func1 {
"in func1"
func2
}
function func2 {
"in func2"
}
workflow1
the error I get is:
The term 'func2' is not recognized as the name of a cmdlet, function, script file, or operable program
I don't understand this. Why would func1 be in scope but not func2? Any help much appreciated. TIA.
回答1:
Think of Workflows as short-sighted programming elements.
A Workflow cannot see beyond what's immediately available in the scope. So nested functions are not working with a single workflow, because it cannot see them.
The fix is to nest workflows along with nested functions. Such as this:
workflow workflow1
{
function func1
{
"in func1"
workflow workflow2
{
function func2
{
"in func2"
}
func2
}
"in workflow2"
workflow2
}
"in workflow1"
func1
}
workflow1
Then it sees the nested functions:
in workflow1
in func1
in workflow2
in func2
More about it here
回答2:
Not really an answer to your question, but more a track to follow. Putting this in a comment would be too long.
From here :
When you run a script workflow, Windows PowerShell parses the script into an abstract syntax tree (AST). The presence of the “workflow” keyword causes the script-to-workflow compiler to use this AST to generate XAML, the format required by the Windows Workflow Foundation runtime. To create the user experience for interacting with this workflow, we then create a wrapper function that has the same parameters – but instead coordinates execution of the workflow within the PowerShell Workflow executive. You can see both the wrapper function and the generated XAML by executing:
Get-Command workflow1 |Format-List *
I did that for your specific workflow (see the workflow1 in the command above) and both XAML and PowerShell generated code are ... interesting. XAML code doesn't include any reference to func2, but contains a reference to func1.
回答3:
To vaguely summarise all the responses, don't question why it behaves this way, just accept that it does and deal with it. Fair enough.
I've written a whole deployment pipeline in none-workflow Powershell and I'd like to optimise it by using workflow's "foreach -parallel" however it seems the tax on doing so is that I'd have to go back and re-write the whole thing in workflow. That's too big a tax to pay unfortunately just to get a parallel foreach loop.
Lesson learned - use Powershell workflow from the get-go.
回答4:
You could wrap the functions and their calls inside an InlineScript - which could be a per-system script. Then run that inlinescript inside a foreach -Parallel loop working through the systems you want to query.
来源:https://stackoverflow.com/questions/27360145/understanding-scope-of-functions-in-powershell-workflow