2012-02-22 79 views
8

我在单个模块中编写了一些与AWS API交谈的PowerShell。我写了一个函数,Get-CloudFormation,它返回CloudFormation的状态。我已经编写了另一个函数Delete-CloudFormation,它在发出删除CF API请求后,尝试开始一个作业,该作业使用我的Get-CloudFormation来轮询CloudFormation的状态。如何调用Start-Job,它取决于调用Start-Job的函数在相同的PowerShell模块中的函数?

我打电话Export-ModuleMemberGet-CloudFormation(但不是Delete-CloudFormation;这是一个私人功能)。 Get-CloudFormation在模块文件的前面定义为Delete-CloudFormation

Start-Job调用(内Delete-CloudFormation)看起来像:

$job = Start-Job -Name "CloudFormationWaitForDeleteSuccess" -ScriptBlock { 
    $status = "" 
    $time = 0 
    while($status -ne "DELETE_COMPLETE") { 
     Write-Verbose ("Checking CloudFormation status") 
     $stack = Get-CloudFormation -accessKey $accessKey -secretKey $secretKey -stackName $stackName 
     $status = $stack.Status 
     Start-Sleep -seconds 10 
     $time += 10 
    } 
    Write-Host "CloudFormation delete-complete after $time seconds $stackName" 
} 

Delete-CloudFormation运行时,我得到一个异常:

The term 'Get-CloudFormation' is not recognized as the name of a cmdlet, 
function, script file, or operable program. Check the spelling of the 
name, or if a path was included, verify that the path is correct and try again. 
+ CategoryInfo   : ObjectNotFound: (Get-CloudFormation:String) [], CommandNotFoundException 
+ FullyQualifiedErrorId : CommandNotFoundException 

为什么?我该如何解决它?

我发现7152090我认为是相似的,但拨打Start-Job-InitializationScript { Get-CloudFormation }给出了大致相同的错误。

如果我打电话给-InitializationScript { Import-Module ".\awsutils.psm1" }开始工作,那么.是我的个人资料的文档目录。即使我将变量绑定到Start-Job之外的Get-Location,并将其称为-InitializationScript { Import-Module "$location\awsutils.psm1" }

回答

5

打动你模块awsutils.psm1在规范路径PowerShell模块:

$env:userprofile\documents\WindowsPowerShell\Modules\awsutils" 

然后初始化启动工作这样

-InitializationScript { Import-Module awsutils } 

与我的自定义模块测试,并开始作业工作。

尝试另外,如果你不想让你的移动PSM1这样的:

-InizializationScript { import-module -name c:\yourpath\yourmodulefolder\ } 

其中yourmoduleforder只包含一个PSM1文件。

+1

我想,如果在OP想成为更有活力的主脚本可以在模块复制到C:\ WINDOWS \ PowerShell模块目录,以便它可以只使用导入模块没有一个完整路径。它可以在以后删除...嘿嘿 – 2012-02-22 13:54:52

+0

当然..这是一个想法! :) – 2012-02-22 13:59:09

2

后台作业是自治的事情。他们不是一个单独的线程共享资源,他们实际上是在一个全新的PowerShell.exe进程中运行。所以我认为你需要在你的脚本块中使用Import-Module来让你在那里获得模块成员。

0

我最终做的是在拨打Start-Job之前设置$env:WhereAmI = Get-Location,然后更改为-InitializationScript { Import-Module "$env:WhereAmI\awsutils.psm1 }。拨打Start-Job后,我拨打Remove-Item env:\WhereAmI进行清理。

(我想这并没有要求我要发展$ PSModulePath内的模块,因为那时源代码控制更多的是有点痛苦成立。一个解决方案)

感谢您的答复。

0
$root = $PSScriptRoot 

$initScript = [scriptblock]::Create("Import-Module -Name '$root\Modules\Publish-Assigned_CB_Reports.psm1'") 

$job1 = Start-Job -InitializationScript $initScript -ScriptBlock {} -ArgumentList 
+0

你能否给你的答案添加一些解释?仅有代码的答案在SO上不受欢迎。 – honk 2015-10-20 20:11:38

相关问题