PowerShell 脚本可以在 ISE 中运行,但在通过文件资源管理器的快捷菜单调用时意外退出

问题描述 投票:0回答:1

我目前正在尝试编写一个脚本,并且对 powershell 还比较陌生

这是下面的脚本

#>
function RunScript {
    # Prompt the user for their username
    $username = Read-Host "Enter your username"

    # Prompt the user for their password
    $password = Read-Host -AsSecureString "Enter your password"

    # Prompt the user for the worker ID
    $workerId = Read-Host "Enter the ID"

    # Create a PSCredential object using the provided username and password
    $credential = New-Object System.Management.Automation.PSCredential($username, $password)

    # Create a new PSSession using the provided credential
    $session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri "LINK/PowerShell/" -Credential $credential

    # Import the PSSession
    Import-PSSession $session

    # Get the AD user and their group membership, then retrieve the distinguished names of the distribution groups
    $groups = Get-ADUser -Identity $workerId | Get-ADPrincipalGroupMembership | Select-Object -ExpandProperty DistinguishedName | Get-DistributionGroup -ErrorAction SilentlyContinue

    # Return the output of the last command
    return $groups
}

# Run the script and store the output
$output = RunScript

# Output the result
Write-Output $output

问题

该脚本在 ISE 中运行良好,但是当右键单击该文件并使用 powershell 运行并输入用户名、密码和workerid 时,需要一些时间,然后我只看到脚本输出大量用户数据,然后窗口关闭。就像命令无法正常工作一样。

powershell output contextmenu microsoft-file-explorer
1个回答
0
投票

通过快捷菜单从文件资源管理器执行 PowerShell 脚本,不幸的是,保留脚本在打开中运行的控制台窗口

因此,为了确保您至少看到以这种方式执行的脚本的输出,您有两个选择:

  • 对于任何给定的脚本,请在脚本末尾放置类似

    Read-Host 'Press Enter to exit.'

     的内容,以防止退出时立即关闭窗口。

  • 更根本的是,您可以将注册表中快捷菜单命令的定义修改为:

    • 两者之一:在每次脚本调用后自动执行此

      Read-Host

       调用

    • 或者:通过进入持久的交互式会话,保持控制台窗口打开,直到明确关闭为止。

    • 两种方法如下所示。


修改
Run with PowerShell
 文件资源管理器快捷菜单命令以保持窗口打开:

说明

  • 第 1 步:定义新命令行。

    • 注:

    • 如果要

      在执行脚本后进入交互式会话,请将 Windows PowerShell CLI(Windows PowerShell CLI)的 -NoExit

       开关放置在 
      powershell.exe 参数之前(
      -File
      也指定为抑制版权信息):
      -NoLogo

      如果您希望
      只等待用户在窗口关闭之前按 
      Enter
    • ,请使用
    • $newCmdLine = '"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -NoLogo -NoExit -File "%1"'

      CLI 参数并附加 -Command 命令: Read-Host

      
      
      
      

      第2步:将新命令行写入注册表:
  • 要修改定义
  • 系统范围

      (对于
    • 所有

      用户),请运行以下命令,这需要提升(以管理员身份运行): $newCmdLine = '"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -Command "& \"%1\"; Read-Host ''Press Enter to exit.''"' 要修改定义

      仅适用于
      当前用户
    • - 不需要提升 - 运行:
    • #requires -RunAsAdministrator Set-ItemProperty registry::HKEY_CLASSES_ROOT\SystemFileAssociations\.ps1\Shell\Windows.PowerShell.Run\Command '(Default)' $newCmdLine

© www.soinside.com 2019 - 2024. All rights reserved.