【问题标题】:Powershell Script how to run multiple lines of code in new powershell window with start-processPowershell Script如何在新的powershell窗口中使用start-process运行多行代码
【发布时间】:2020-01-28 13:38:13
【问题描述】:

我有一个基本菜单脚本,其中包含显示有关特定计算机的信息的选项,启动脚本时会提示用户输入域管理员权限和计算机名(计算机名保存在 $ComputerName 中),并且按预期工作。

脚本中的所有选项都会使用 Start-Process 打开第二个窗口,在该窗口中执行代码。

示例:

start-process powershell.exe -argument "-noexit -nologo -noprofile -command

我希望脚本中的第一个选项打开一个新窗口,运行

Get-WmiObject Win32_PhysicalMemory -computername $ComputerName

并获取 RAM 零件号(将其放入 $Partnumber 中),并为用户提供使用 Google 在 Chrome 中查找的选项。

我的问题是(除了是编码新手)只有第一行代码在新窗口中运行,其余代码似乎恢复到主窗口。

第一个选项如下所示:

start-process powershell.exe -argument "-noexit -nologo -noprofile -command Get-WmiObject Win32_PhysicalMemory -computername $ComputerName"
$ToChrome = Read-Host 'Do you wish to Google the partnumber? Y or N'
if ($ToChrome -eq 'j') {
    $Partnumber = Get-WmiObject Win32_PhysicalMemory -computername $ComputerName | select -expandproperty Partnumber
    Start-Process "chrome.exe" ("https://www.google.com/?q=$Partnumber")
} 

if ($ToChrome -eq 'n') {
    Continue
}

所有 RAM 信息都显示在“新窗口”中,但主窗口上显示“Google it”提示,有没有办法解决这个问题,以便所有代码行运行在“新窗口”中?

顺便说一句,这是我的第一篇文章。

【问题讨论】:

    标签: powershell start-process get-wmiobject


    【解决方案1】:

    如果您想在新窗口中完成所有操作,请创建一个脚本并在一次调用 Start-Process 时执行它

    $script = {
      $ComputerName = $env:COMPUTERNAME  
      $ToChrome = Read-Host 'Do you wish to Google the partnumber? Y or N'
      if ($ToChrome -eq 'j') {
        $Partnumber = (Get-WmiObject Win32_PhysicalMemory -computername $ComputerName | select -expandproperty PartNumber)[0]
    
        Start-Process "chrome" "https://www.google.com/search?q=$Partnumber"
      } 
    }
    
    Start-Process powershell -ArgumentList $script
    

    顺便说一句...使用 google.com/search?q= 实际上会开始搜索,而不是在搜索框中打开带有部件号的 chrome 到 google 站点。

    【讨论】:

    • 感谢您的回答,非常感谢,Google 搜索提示很棒 :-)。
    • 我是否正确假设 "$Computername = $env:COMPUTERNAME" 将 $Computername 变量设置为运行此脚本的计算机的名称?。
    • 您正在运行的脚本在运行此脚本的计算机上。即使您使用Invoke-Command -computername xyz { $using:script } 在远程计算机上执行此脚本,$computername 也将是该远程系统名称。
    猜你喜欢
    • 2018-06-15
    • 2019-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-05
    • 2019-12-05
    • 1970-01-01
    相关资源
    最近更新 更多