【问题标题】:Is there any way to tell what script is running when started with start-job -filename?有什么方法可以告诉以 start-job -filename 启动时正在运行的脚本是什么?
【发布时间】:2011-05-12 18:12:44
【问题描述】:

我正在使用类似于以下命令的内容开始 PowerShell 作业:

start-job -filename my_script.ps1 -argumentlist ($v1, $v2, $v3)

然而,这个脚本需要知道它的位置,因为它会根据相对于它的位置运行其他命令。当直接从提示符运行时,这些结构会起作用:

join-path (split-path (& { $myinvocation.scriptname })) "relative path\filename"
join-path (split-path $myinvocation.mycommand.definition) "relative path\filename"

但是,当作为第一个示例中的作业开始时,这根本不起作用。当我开始工作时,如何确定我从哪里开始?

【问题讨论】:

    标签: powershell powershell-jobs


    【解决方案1】:

    这似乎类似于远程处理情况,其中文件作为脚本块传递到作业中,因此脚本来自哪个文件的概念会丢失。您也可以通过路径(尽管这似乎不太理想):

    PS> gc .\job.ps1
    param($scriptPath)
    "Running script $scriptPath"
    PS> $job = Start-Job -FilePath .\job.ps1 -ArgumentList $pwd\job.ps1
    PS> Wait-Job $job
    
    Id  Name            State      HasMoreData     Location  Command
    --  ----            -----      -----------     --------  -------
    13  Job13           Completed  True            localhost param($scriptPath)...
    
    
    PS> Receive-Job $job.id
    Running script C:\Users\hillr\job.ps1
    

    【讨论】:

      【解决方案2】:

      更新:

      我遇到了这个代码示例:

      http://blog.brianhartsock.com/2010/05/22/a-better-start-job-cmdlet/

      为了使用 FilePath 参数而不是 ScriptBlock,我将其修改为:

      param([string]$file)
      
      $filePath = split-path $file -parent
      Start-Job -Init ([ScriptBlock]::Create("Set-Location $filePath")) -FilePath $file -ArgumentList $args
      

      这将被称为:

      Start-JobAt c:\full_path\to\file\my_script.ps1 ($v1, $v2, $v3)
      

      使用 -Init (-InitializationScript) 并触发 Set-Location 将当前执行进程移动到脚本的目录,因此,您可以从那里确定相对位置。

      正如博文所述,您可以将其作为外部脚本(我将我的测试为 Start-JobAt.ps1)或将其作为您的用户/服务帐户配置文件的一部分。

      【讨论】:

      • 我不想要“当前工作目录”,我想要“当前执行脚本所在的目录”。
      • 啊,哎呀——错过了。更新了回复。
      • 是的,不太理想。我最终只是将脚本的路径作为参数传递。
      猜你喜欢
      • 2019-07-27
      • 2016-03-22
      • 2013-04-21
      • 2010-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-07
      • 2015-11-07
      相关资源
      最近更新 更多