在新的,干净的PowerShell实例中调用PowerShell脚本(在另一个脚本中)

Vim*_*mes 8 powershell

我有很多脚本.在进行更改后,我喜欢运行它们以查看是否有任何损坏.我写了一个脚本来循环遍历每个,在新数据上运行它.

在我的循环中,我正在运行powershell.exe -command <path to script>.我不知道这是否是最好的方法,或者两个实例是否彼此完全分开.

在一个干净的PowerShell实例中运行脚本的首选方法是什么?或者我应该说"会话"?

Rom*_*min 8

当然,使用powershell.exe似乎是一种很好的方法,但有其优点和缺点.

优点:

  • 每个脚本都在一个单独的干净会话中调用.
  • 即使崩溃也不会停止整个测试过程.

缺点:

  • 调用powershell.exe有点慢.
  • 测试取决于退出代码,但0并不总是意味着成功.

没有提到的缺点是一个潜在的问题.

演示脚本如下.它已经过PS v2和v3测试.脚本名称可能包含特殊字符,如空格,撇号,括号,反引号,美元.注释要求中提到的一个是在代码中获取脚本路径的能力.通过提出的方法,脚本可以获得自己的路径 $MyInvocation.MyCommand.Path

# make a script list, use the full paths or explicit relative paths
$scripts = @(
    '.\test1.ps1' # good name
    '.\test 2.ps1' # with a space
    ".\test '3'.ps1" # with apostrophes
    ".\test [4].ps1" # with brackets
    '.\test `5`.ps1' # with backticks
    '.\test $6.ps1' # with a dollar
    '.\test ''3'' [4] `5` $6.ps1' # all specials
)

# process each script in the list
foreach($script in $scripts) {
    # make a command; mind &, ' around the path, and escaping '
    $command = "& '" + $script.Replace("'", "''") + "'"

    # invoke the command, i.e. the script in a separate process
    powershell.exe -command $command

    # check for the exit code (assuming 0 is for success)
    if ($LastExitCode) {
        # in this demo just write a warning
        Write-Warning "Script $script failed."
    }
    else {
        Write-Host "Script $script succeeded."
    }
}
Run Code Online (Sandbox Code Playgroud)


Kei*_*ill 6

如果您使用的是PowerShell 2.0或更高版本,则可以使用作业执行此操作.每个作业都在单独的PowerShell进程中运行,例如:

$scripts = ".\script1.ps1", ".\script2.ps1"

$jobs = @()
foreach ($script in $scripts)
{
    $jobs += Start-Job -FilePath $script
}

Wait-Job $jobs

foreach ($job in $jobs)
{
    "*" * 60
    "Status of '$($job.Command)' is $($job.State)"
    "Script output:"
    Receive-Job $job
}
Run Code Online (Sandbox Code Playgroud)

另外,请查看PowerShell社区扩展.它有一个Test-Script可以检测脚本文件中语法错误的命令.当然,它不会捕获运行时错误.