Powershell中的背景工作

Bri*_*ian 7 powershell background process start-job

我正在尝试在后台运行一个带有参数的.exe并且目标有空格的作业.例如:

$exec = "C:\Program Files\foo.exe"
Run Code Online (Sandbox Code Playgroud)

我想用参数运行它:

foo.exe /param1 /param2, etc.
Run Code Online (Sandbox Code Playgroud)

我知道这样Start-Job做但我已经尝试了很多不同的组合,它或者由于白色空间或参数而给我一个错误.有人可以帮我解决这里的语法吗?我需要假设这$exec是可执行文件的路径,因为它是配置文件的一部分,可能会在以后更改.

And*_*ndi 8

一种方法是使用带有param块的脚本块.

如果存在一个带有空格的单个参数,例如文件/文件夹路径,则应引用该参数将其视为单个项目.参数是传递给脚本块的数组.

此示例使用脚本块,但您也可以使用cmdlet的参数而不是-FilePath参数来使用PowerShell脚本.Start-Job-ScriptBlock

这是另一个带空格参数的例子:

$scriptBlock = {
    param (
        [string] $Source,
        [string] $Destination
    )
    $output = & xcopy $Source $Destination 2>&1
    return $output
}

$job = Start-Job -scriptblock $scriptBlock -ArgumentList 'C:\My Folder', 'C:\My Folder 2'
Wait-Job $job
Receive-Job $job
Run Code Online (Sandbox Code Playgroud)

下面是使用$args内置变量而不是param块的示例.

$scriptBlock = {
    $output = & xcopy $args 2>&1
    return $output
}

$path1 = "C:\My Folder"
$path2 = "C:\My Folder 2"

"hello world" | Out-File -FilePath  "$path1\file.txt"

$job = Start-Job -scriptblock $scriptBlock -ArgumentList $path1, $path2
Wait-Job $job
Receive-Job $job
Run Code Online (Sandbox Code Playgroud)