我目前正在尝试编写一个脚本,并且对 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 脚本,不幸的是,不保留脚本在打开中运行的控制台窗口。
因此,为了确保您至少看到以这种方式执行的脚本的输出,您有两个选择:
Read-Host 'Press Enter to exit.'
的内容,以防止退出时立即关闭窗口。
Read-Host
调用
Run with PowerShell
文件资源管理器快捷菜单命令以保持窗口打开:
旧版,仅限 Windows 的 PowerShell 版本(与按需安装、跨平台 PowerShell (Core) 7+ 版本相反)。
说明:
-File
或
-Command
之前添加
-NoProfile
。
在执行脚本后进入交互式会话,请将 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