【问题标题】:Powershell: calling one function from another and second function triggers a backgroud runPowershell:从另一个函数调用一个函数,第二个函数触发后台运行
【发布时间】:2019-08-01 14:06:04
【问题描述】:

我正在尝试做类似的事情。 第一个功能 第二个函数调用第一个函数并触发 Start-Job

示例:

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 

} Start-Job -ScriptBlock $scriptBlock -ArgumentList @($RootPath) }
}

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

确切的错误sn-p

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> 

【问题讨论】:

  • 我想在后台运行上面的函数 CreateDeleteDirs (直到外部杀死)。在独立中调用函数 CreateDeleteDirs 工作正常
  • CreateDeleteDirsCreateDeleteDir ;)
  • 对不起,我在这里输入错误,名称相同“CreateDeleteDirs”

标签: powershell


【解决方案1】:

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

$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

【讨论】:

  • 谢谢!但是我不能通过这个结构进一步使用 CreateDeleteDirs 作为一个单独的函数
猜你喜欢
  • 1970-01-01
  • 2022-08-04
  • 1970-01-01
  • 2020-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多