Powershell中的后台作业 [英] Background Job in Powershell

查看:88
本文介绍了Powershell中的后台作业的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to run a job in a background which is a .exe with parameters and the destination has spaces. For example:

$exec = "C:\Program Files\foo.exe"

我想使用参数运行它:

foo.exe /param1 /param2, etc.

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

I know that Start-Job does this but I've tried tons of different combinations and it either gives me an error because of the white space or because of the parameters. Can someone help me out with the syntax here? I need to assume that $exec is the path of the executable because it is part of a configuration file and could change later on.

推荐答案

一种方法是使用脚本块和参数块.

One way to do this is use a script block with a param block.

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

If there is a single argument with a space in it such as a file/folder path it should be quoted to treat it as a single item. The arguments are an array passed to the script block.

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

This example uses a script block but you can also use a PowerShell script using the -FilePath parameter of the Start-Job cmdlet instead of the -ScriptBlock parameter.

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

Here is another example that has arguments with spaces:

$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

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

Here is an example using the $args built-in variable instead of the param block.

$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

这篇关于Powershell中的后台作业的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆