2013-09-25 82 views
1

我有一個帶有工作流和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 executor,BookmarkManager bookmarkManager)

這可能嗎?我究竟做錯了什麼?

+0

[在PowerShell中的工作流功能的理解範圍]的可能的複製(http://stackoverflow.com/questions/27360145/understanding-scope-of-functions-in-powershell-workflow) – stijn

回答

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