首页 > 解决方案 > Powershell命令执行顺序问题

问题描述

我是学习 Powershell 的新手,遇到了一个让我发疯的问题。我想写一个简单的 Powershell 脚本,可以用来获取某些 ActiveDirectory 用户的组成员资格,以及某些 ActiveDirectory 组的用户,最后提供在控制台上写入结果或保存的选项作为.csv。一切都很好,除了无论我做什么,我都无法阻止窗口在将结果写入控制台后立即关闭。我知道我可以从命令行以不允许关闭窗口的方式运行 PS1,但我希望 Powershell 自己完成。

我尝试在查询脚本之后同时使用“暂停”和读取主机,但是停止事件总是在结果出现在控制台之前发生,无论它们两者之间的顺序是什么。我根本无法理解为什么这两个命令的执行顺序是向后的。您能给我一些见解,为什么 Powershell 会这样做吗?

$nameofgroup = Read-Host -Prompt "`nPlease enter the name of the group!`n"
Get-ADGroupMember -identity $nameofgroup | Get-ADObject -Properties description, samAccountName | select @{n='Name'; e='name'}, @{n='Description'; e='description'}, @{n='Username'; e='samAccountName'}
$temp = Read-Host "Press Enter to continue..."

标签: powershell

解决方案


所以你需要明确告诉powershell输出字符串。我还为您添加了一些错误处理,因此您不必每次都运行脚本。就像组输入错误或不存在一样。

Do
{
    $nameofgroup = Read-Host -Prompt "`nPlease enter the name of the group!`n"

    try
    {
        Get-ADGroupMember -identity $nameofgroup | Get-ADObject -Properties description, samAccountName | select @{n='Name'; e='name'}, @{n='Description'; e='description'}, @{n='Username'; e='samAccountName'} | Out-String
        $errorMessage = 'False'
        Read-Host -Prompt 'Press Enter key to exit'
    }
    catch
    {
        Write-Host "Could not find group please try again"
        $errorMessage = 'True'
    }
}
while($errorMessage -eq 'True')

推荐阅读