【问题标题】:Using a global function within a workflow/function在工作流/函数中使用全局函数
【发布时间】:2013-09-26 01:52:08
【问题描述】:

我有一个带有工作流和 2 个简单函数的 Windows PowerShell 3.0 脚本。如果没有工作流,我可以在 DoSomething 函数中使用我的 Log 函数,但不能使用工作流。脚本是:

function DoSomething()
{
    # This is NOT logged
    Log("This will fail...")
}

function global:Log([string]$Message)
{
    Add-Content -Path "C:\my.log" -Value $Message
}

workflow New-CustomWorkflow
{
    try
    {
        # This is logged
        Log("Starting with the workflow")
        DoSomething
    }
    catch
    {
        # This is logged
        Log($_)
    }
}

New-CustomWorkflow

my.log的内容是这样的:

从工作流程开始
System.Management.Automation.RemoteException:术语“日志”未被识别为 cmdlet、函数、脚本文件或可运行程序的名称。检查名称的拼写,或者如果包含路径,请验证路径是否正确并重试。 在 Microsoft.PowerShell.Activities.PSActivity.OnResumeBookmark(NativeActivityContext 上下文,书签书签,对象值) 在 System.Activities.Runtime.BookmarkCallbackWrapper.Invoke(NativeActivityContext 上下文,书签书签,对象值) 在 System.Activities.Runtime.BookmarkWorkItem.Execute(ActivityExecutor 执行器, BookmarkManager bookmarkManager)

这可能吗?我做错了什么?

【问题讨论】:

标签: powershell powershell-3.0


【解决方案1】:

在工作流中,您调用的大部分内容都是工作流活动,包括诸如 try/catch 之类的内容以及看似 PowerShell 命令的内容。要查看幕后发生的事情,请尝试以下操作:

(Get-Command New-CustomWorkflow).XamlDefinition

现在等着你的脑袋爆炸吧。 :-)

顺便说一句,您可以拥有嵌套的函数和工作流程。这对我有用:

workflow New-CustomWorkflow
{
    function DoSomething()
    {
        workflow Log([string]$Message)
        {
            Add-Content -Path "$home\my.log" -Value $Message
        }

        # This is NOT logged
        Write-Output -InputObject "In DoSomething"
        Log -Message "This will fail..."
    }

    try
    {
        # This is logged
        Write-Output -InputObject "Before inline"
        Log -Message "Starting with the workflow"
        Write-Output -InputObject "After inline"
        DoSomething
    }
    catch
    {
        # This is logged
        Write-Output -Input "Doh $_"
        Log -Message $_
    }
}

New-CustomWorkflow

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-16
    相关资源
    最近更新 更多