代码之家  ›  专栏  ›  技术社区  ›  Mark

当使用start job-filename启动时,是否有任何方法可以告诉正在运行的脚本?

  •  2
  • Mark  · 技术社区  · 15 年前

    我正在使用以下命令启动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"
    

    然而,当作为一项工作开始时,这根本不起作用,如第一个例子所示。当我刚开始工作的时候,我如何确定我从哪里跑出来?

    2 回复  |  直到 15 年前
        1
  •  2
  •   Keith Hill    15 年前

    这看起来像远程处理,文件作为脚本块传递到作业中,这样脚本来自哪个文件的概念就丢失了。你也可以走这条路(尽管这看起来不太理想):

    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
  •  0
  •   David R. Longnecker    15 年前

    更新时间:

    我遇到了一个代码示例:

    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)并关闭设置位置会将当前正在执行的进程移动到脚本的目录中,因此,可以从中确定相对位置。

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

    推荐文章