首页 > 解决方案 > 从 CMD 运行 PowerShell 脚本(棘手的一个)

问题描述

我知道这听起来可能像是以前的问题(部分是真的)。然而,我在这里有一个有趣的转折。

需要的流程:
从 CMD 运行 Powershell 脚本。看起来微不足道,实际上正在工作,传递参数等......
但是......
我的powershell脚本中有一个Start-Job,因为我希望它异步运行。

#######################################################################

   #$DropLocation = "SOME UNC PATH"
   #$buildid = "SOME VERSION"
param (
        [parameter(Mandatory = $true)][string]$DropLocation,
        [parameter(Mandatory = $true)][string]$buildid
       ) 


Start-Job -Name Upload `
-ScriptBlock {

param (
        [parameter(Mandatory = $true)][string]$DropLocation,
        [parameter(Mandatory = $true)][string]$buildid
       ) 
Write-Output "asd"
$buildpath = $DropLocation+"\"+$buildid
$logs = gci $buildpath"\logs" -Name "ActivityLog.AgentScope*.xml"

#Start-Sleep -Seconds 300

if ($logs.PSPath -gt 0)
    { 
        $destination = $env:TEMP+"\Config\"
        Copy-Item $logs.PSPath "$destination $buildid.xml"
    }
} `
-ArgumentList $DropLocation,$buildid

#######################################################################

我正在使用 Param 从外部获取,然后再次在 Start-Job 中,以便 Async 作业获取其参数

此脚本保存为SCRIPTNAME.ps1,我正在尝试从 CMD 运行它。

从 cmd(以管理员身份运行)

powershell "& "C:\temp\SCRIPTNAME.ps1" "SOME UNC PATH" "SOME VERSION""

或者

powershell -file "C:\temp\SCRIPTNAME.ps1" "SOME UNC PATH" "SOME VERSION"

什么都没发生。
然而,从PowerShell ISE来看,一切都运行良好

非常感谢您的帮助!

标签: windowspowershellcmdcommand-line

解决方案


powershell -noexit ". C:\temp\SCRIPTNAME.ps1"

Dot source it, this will change the scope of the sourced function for your job to work within the currently running script's scope while allowing you to run multiple threads also.


推荐阅读