【问题标题】:Start-Process and powershell.exe with splattingStart-Process 和 powershell.exe 与 splatting
【发布时间】:2019-09-30 16:36:13
【问题描述】:

几天来,我一直在尝试多线程 WPF GUI,一旦单击按钮,它将运行 PS3.0 脚本。我不能使用 start-job,因为我必须跟踪(一次多个会话),但是,我想只在 PS 的单独进程中运行脚本 - 就好像我要从一个捷径。并且能够只打开一个 PS 窗口来跟踪脚本本身的进度。

预期结果将是在 powershell.exe 会话中启动脚本并传递 3 个参数 - 2 个字符串和 1 个布尔值。由用户提供。

所以在 ISE 中:

C:\temp\test.ps1 -argumentlist $computername $username $citrixtest

工作正常。 我花了几个小时在互联网上搜索,只是为了找到一个推荐开始工作的线程或使用后台工作人员的方法——这不是我想要的脚本。

所以我猜想点击按钮的调用会是类似的(我尝试过的一些事情)

$ComputerName = "testtext1"
$UserName = "testtext2"
$CitrixTest = $True

$command = "c:\temp\test.ps1"
$arg = @{
    Computername = "$computername";
    Username = "$username";
    CitrixTest = "$citrixtest"
}

#$WPFStartButton.Add_Click({
    Start-Process powershell -ArgumentList "-noexit -command & {$command} -argumentlist $arg"
#})

不向 test.ps1 传递参数——但是,它正在进入“暂停”——因此脚本成功启动。

test.ps1 在哪里

$ComputerName 
$UserName 
$CitrixTest 
pause

来电者:

function Caller {
Param (
    $ScriptPath = "c:\temp\test.ps1"
)

$Arguments = @()
$Arguments += "-computername $ComputerName"
$Arguments += "-UserName $UserName"
$Arguments += "-citrixtest $citrixtest"
$StartParams = @{   
    ArgumentList = "-File ""$ScriptPath""" + $Arguments
}
    Start-Process powershell @StartParams
}
Caller

不完全启动脚本 - PS 窗口只是关闭 - 可能找不到 .ps1 脚本的路径。

另一种方法也在脚本中启动但不传递参数

$scriptFile = '"C:\temp\test.ps1"'
[string[]]$argumentList = "-file"
$argumentList +=  $scriptFile
$argumentlist += $computername
$argumentlist += $UserName
$argumentlist += $CitrixTest

$start_Process_info =  New-Object System.Diagnostics.ProcessStartInfo
$start_Process_info.FileName = "$PSHOME\PowerShell.exe"
$start_Process_info.Arguments = $argumentList


$newProcess = New-Object System.Diagnostics.Process
$newProcess.StartInfo = $start_Process_info

$newProcess.Start() | Out-Null

有没有办法让这项工作如我所愿?还是我应该深入挖掘运行空间并尝试一下?

【问题讨论】:

  • 所以...麻烦Start-Process 不起作用?请用问题/错误消息更新问题?还是Click() 处理程序的问题(即做一个基本的Write-Host "Hello World" 测试)?还可以尝试输出变量的基本Click() 处理程序测试。可能变量没有被设置/传递给Click()处理程序来启动Start-Process
  • 与点击无关,只是它最终会调用它。我需要运行: C:\temp\test.ps1 -argumentlist $computername $username $citrixtest 作为单独的 powershell.exe 会话。不使用启动作业。第一个脚本根本没有将参数传递给 test.ps1 脚本第二个似乎没有工作(完全启动和关闭 - 很可能找不到路径)第三个根本没有再次将参数传递给 test.ps1脚本
  • 你的脚本有一个参数叫-argumentlist?

标签: powershell


【解决方案1】:

@Bill_Stewart 我刚刚意识到我没有将参数(args)放在我的脚本中...... 这就是为什么它不会像我希望的那样提取这些变量。我将不得不检查我什么时候回到办公室,如果这正是我所缺少的。

检查了我运行 PS 5.1 的笔记本电脑,这似乎按预期工作

$testarg = @(
    '-File'
    "C:\temp\test.ps1"
    "$computername"
    "$username"
    "$citrixtest"
)

Start-Process powershell.exe -ArgumentList $testarg

test.ps1 在哪里:

param(
$ComputerName,
$UserName,
$citrixtest
)

$ComputerName 
$UserName 
$CitrixTest 
pause

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多