Powershell:从另一个函数调用另一个函数会触发背景运行

时间:2019-03-11 09:32:42

标签: powershell

我正在尝试做类似的事情。 第一功能 第二个功能调用第一个功能并触发开始作业

示例:

Function CreateDeleteDirs {
Param(
  [Parameter(
  Mandatory = $True,
  HelpMessage = 'Remote Path to create dirs on. Provide full path.')
  ]
  [ValidateNotNullOrEmpty()]
  [string]$RootPath
  )
  ***do some stuffs***
}
Function CreateDeleteDirBack {
Param(
  [Parameter(
  Mandatory = $True,
  HelpMessage = 'Remote Path to create dirs on. Provide full path.')
  ]
  [ValidateNotNullOrEmpty()]
  [string]$RootPath
  )
  $scriptBlock = {
 param ($RootPath)
 CreateDeleteDirs -RootPath $RootPath 

}   开始作业-ScriptBlock $ scriptBlock -ArgumentList @($ RootPath)     }
}

所以从第二个函数调用CreateDeleteDirs总是失败。我该怎么做

确切的错误代码段

PS C:\Program Files\WindowsPowerShell\Modules> CreateDeleteDirsBackground -RootPath Y: 

Id     Name            PSJobTypeName   State         HasMoreData     Location             Command                  
--     ----            -------------   -----         -----------     --------             -------                  
21     Job21           BackgroundJob   Running       True            localhost            ...                      



PS C:\Program Files\WindowsPowerShell\Modules> Receive-Job Job21
The term 'CreateDeleteDirs' 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: (CreateDeleteDirs:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException
    + PSComputerName        : localhost


PS C:\Program Files\WindowsPowerShell\Modules> 

1 个答案:

答案 0 :(得分:0)

我已经修改了您的代码以输出根路径,以便我们可以看到它正在工作并等待作业完成。

$script_block = {
  function CreateDeleteDirs {
    Param(
      [Parameter(Mandatory = $True, HelpMessage = 'Remote Path to create dirs on. Provide full path.')]
      [ValidateNotNullOrEmpty()]
      [string]$RootPath
    )

    write-host "Rootpath = '$RootPath'"
  }

  function CreateDeleteDirBack  {
    Param(
      [Parameter(Mandatory = $True, HelpMessage = 'Remote Path to create dirs on. Provide full path.')]
      [ValidateNotNullOrEmpty()]
      [string]$RootPath
    )

    CreateDeleteDirs -RootPath $RootPath 
  } 
}

Start-Job -InitializationScript $script_block -ScriptBlock {CreateDeleteDirBack  'foo'} | Wait-Job | Receive-Job