简体   繁体   English

如何使Powershell以逗号分隔输出Get-ADUser -Filter *?

[英]How do I get Powershell to output Get-ADUser -Filter * as comma delimited?

I have a simple Powershell script that I want to use to grab all the users in AD and show specific properties. 我有一个简单的Powershell脚本,我想用它来捕获AD中的所有用户并显示特定的属性。 Here is the heart of my script: 这是我脚本的核心:

$id = "*"
Get-ADUser -Filter {SAMAccountName -like $id} -Properties * | Select-Object -Property SAMAccountName,Name,PasswordNeverExpires,LockedOut,PasswordLastSet,LastLogOnDate,CanonicalName 

The full script has an input parameter to set $id so that it can be a single ID, a list of IDs (such as "bsmith, jdoe, gmanning"), or * to get all accounts. 完整脚本具有一个输入参数来设置$ id,以便它可以是单个ID,ID列表(例如“ bsmith,jdoe,gmanning”)或*以获取所有帐户。

Here's my problem: When using, *, I need this to output as comma delimited. 这是我的问题:使用*时,我需要此输出以逗号分隔。

Here's the catch: The output cannot be to a CSV file--or any other type of file. 要注意的是:输出不能到CSV文件或任何其他类型的文件。

The reason being is that I'm writing this script to be used on N-Enable's N-Central monitoring suite of software. 原因是我正在编写此脚本以用于N-Enable的N-Central监视软件套件。 You don't need to know N-Central to help with my problem, just understand that N-Central uses its own software to run Powershell scripts on clients and returns the results into a txt file that cannot be changed to a csv file (or formatted in any other way than what it has hard-coded). 您不需要了解N-Central即可解决我的问题,只需了解N-Central使用其自己的软件在客户端上运行Powershell脚本并将结果返回到无法更改为csv文件的txt文件中即可(或除了硬编码以外,其他任何方式都无法格式化。

What this means is that my results have to either be what would show up on the screen or in a variable (such as $results=Get-ADUser -Filter * ....). 这意味着我的结果必须是屏幕上显示的值或变量中的值(例如$ results = Get-ADUser -Filter * ....)。 I cannot output to any type of file, which leaves out Export-CSV as an option. 我无法输出到任何类型的文件,因此没有Export-CSV作为选项。

I've tried other types of formatting to no avail (such as with -f). 我尝试了其他类型的格式化都没有用(例如,使用-f)。 The issue seems to be with the way Powershell grabs all AD Users using the * wildcard. 问题似乎与Powershell使用*通配符捕获所有AD用户的方式有关。 It seems to grab them all as one big object, so I am unable to get my output to have a comma between all the properties so that I get a comma-delimited output. 似乎将它们全部当作一个大对象抓住了,所以我无法使我的输出在所有属性之间都具有逗号,因此我得到了以逗号分隔的输出。 Thus, when I get the results back from N-Central as a .txt file, all the data is there, but there are no commas in between the properties for me to then open the .txt file as comma-delimited in Excel (or tab-delimited for that matter). 因此,当我从N-Central以.txt文件的形式返回结果时,所有数据都已存在,但是在属性之间没有逗号,因此我可以在Excel中以逗号分隔的方式打开.txt文件(或制表符分隔的内容)。

Does anyone have a solution that will allow me to format Get-ADUser -filter * so that it is comma-delimited without using export to file? 有没有人有一种解决方案,可以让我格式化Get-ADUser -filter *,使其以逗号分隔,而无需使用导出到文件?

UPDATE: Ok, I thought I was keeping things easy by not posting my full script but it seems I've done the opposite. 更新:好的,我想通过不发布完整脚本来使事情变得容易,但似乎我做了相反的事情。 So, below is my full script. 因此,以下是我的完整脚本。 Anyone should be able to run this to see the results: 任何人都应该可以运行它来查看结果:

function Get-ADUserInfo
{
    [CmdletBinding()]
    param(
        #[Parameter(Mandatory=$True)]
        [string[]]$Users= '*'

    )
    Begin {

        $maxPasswordAge = (Get-ADDefaultDomainPasswordPolicy).MaxPasswordAge.Days
        $Headers="ID, Name, Password Never Expires?, Locked Out, Password Last Set, Expiry Date, Last Logon Date, OU Path"

    }
    Process {
        foreach ($id in $Users)
        {
            $results=Get-ADUser -Filter {SAMAccountName -like $id} -Properties * | select -property SAMAccountName,Name, PasswordNeverExpires,LockedOut,PasswordLastSet,(@{Expression={$_.PasswordLastSet.AddDays($maxPasswordAge)}}), LastLogOnDate,CanonicalName  | `
        ConvertTo-CSV -NoTypeInformation 

        }

    }
    End {
        $Headers
        $results
        }
}

Get-ADUserInfo -Users

Some notes: 一些注意事项:

  1. When calling Get-AdUserInfo -Users, the script needs to work by entering a single ID, *, or multiple IDs separated by a comma when using the -Users parameter. 调用Get-AdUserInfo -Users时,脚本需要通过使用-Users参数输入单个ID,*或多个用逗号分隔的ID来工作。
  2. Using ConvertTo-CSV solved my biggest problem, comma separated output,thanks all. 使用ConvertTo-CSV解决了我最大的问题,用逗号分隔输出,谢谢。
  3. I'd like to get rid of the headers that are auto-created as well ("SAMAccountName","Name","PasswordNeverExpires","LockedOut","PasswordLastSet","$_.PasswordLastSet.AddDays($maxPasswordAge)","LastLogOnDate","CanonicalName"). 我也想摆脱自动创建的标头(“ SAMAccountName”,“ Name”,“ PasswordNeverExpires”,“ LockedOut”,“ PasswordLastSet”,“ $ _。PasswordLastSet.AddDays($ maxPasswordAge)” ,“ LastLogOnDate”,“ CanonicalName”)。 How can I do that? 我怎样才能做到这一点? I've tried -skip 1 but that doesn't work with * and removes everything (including the data) if used with a single ID or IDs separated with commas. 我试过了-skip 1,但是不适用于*,并且如果使用单个ID或用逗号分隔的ID,则将删除所有内容(包括数据)。 I can't get -ExpandProperty to work either. 我也无法使-ExpandProperty正常工作。 Adding format-table -hidetableheaders at the end doesn't do anything as well 最后添加format-table -hidetableheaders并没有做任何事情
$id = "*"
$userlist = Get-ADUser -Filter {SAMAccountName -like $id} -Properties  SAMAccountName,Name,PasswordNeverExpires,LockedOut,PasswordLastSet,LastLogOnDate,CanonicalName | ConvertTo-CSV -NoTypeInformation

$userlist will be an array of users stored in CSV formatted lines $ userlist将是以CSV格式存储的用户数组

Edit: Combined -Properties * | 编辑:组合属性* | Select [propertylist] and get rid of the pull of all properties. 选择[propertylist]并摆脱所有属性的影响。

Edit: included -NoTypeInformation so that the output is pure CSV. 编辑:包括-NoTypeInformation,以便输出为纯CSV。

Note: Something should be done about the filter. 注意:应该对过滤器做一些事情。

So you could use something like this then 所以你可以使用这样的东西

$props = "SAMAccountName","Name","PasswordNeverExpires","LockedOut","PasswordLastSet","LastLogOnDate","CanonicalName"
$results = Get-ADUser -Filter * -Properties $props | Select $props | ConvertTo-Csv -NoTypeInformation

This uses the $props array to make the actual query readable and enforce property order. 这使用$props数组使实际查询可读并强制执行属性顺序。 Most of those properties are returned by default, like samaccountname , so it is not required to specify them but no harm done. 这些属性中的大多数都是默认情况下返回的,例如samaccountname ,因此不需要指定它们,但不会造成损害。

$results would contain a quoted comma delimited output. $results将包含一个用引号引起来的逗号分隔输出。 If the quotes bother you they should be removed with a simple -replace 如果引号困扰您,则应使用简单的-replace将其删除

$results = $results -replace '"'

Aside 在旁边

As others have mentioned you are wasting time using -Properties * you should only return the properties that you need. 正如其他人提到的那样,您在浪费-Properties *时间,应该只返回所需的属性。 Which is, again, why I used $props . 同样,这就是为什么我使用$props

Update from comments 来自评论的更新

If you want to remove the header column you just need to -Skip that from the output. 如果要删除标题列,只需要从输出中-Skip At the end of the code that populates results just add Select-Object 在填充结果的代码末尾,只需添加Select-Object

$results = Get-ADUser -Filter * -Properties $props | Select $props | ConvertTo-Csv -NoTypeInformation | Select-Object -Skip 1

Also to cover your calculated property the easiest way that I have found so far is to add another Select-Object . 同样,要覆盖您的计算属性,到目前为止我发现的最简单的方法是添加另一个Select-Object Not the way I would want to but for now it works. 不是我想要的方式,但是现在它可以了。

$results = Get-ADUser -Filter * -Properties $props | 
    Select $props | Select-Object *,@{L="pWD";Expression={$_.PasswordLastSet.AddDays($masPasswordAge)}} | 
    ConvertTo-Csv -NoTypeInformation | Select-Object -Skip 1

Game Changer 改变游戏规则

So you made some pretty big changes to your example by including your function. 因此,您通过包含函数对示例进行了相当大的更改。 Try this on for size now. 立即尝试此尺寸。

function Get-ADUserInfo
{
    [CmdletBinding()]
    param(
        #[Parameter(Mandatory=$True)]
        [string[]]$Users= '*'

    )
    Begin{
        $results = @()
        $maxPasswordAge = (Get-ADDefaultDomainPasswordPolicy).MaxPasswordAge.Days
        $Headers= @{Label="ID";Expression={$_.SAMAccountName}},
        @{Label="Name";Expression={$_.Name}},
        @{Label="Password Never Expires?";Expression={$_.PasswordNeverExpires}},
        @{Label="Locked Out";Expression={$_.LockedOut}},
        @{Label="Password Last Set";Expression={$_.PasswordLastSet}},
        @{Label="Expiry Date";Expression={$_.PasswordLastSet.AddDays($maxPasswordAge)}},
        @{Label="Last Logon Date";Expression={$_.LastLogOnDate}},
        @{Label="OU Path";Expression={$_.CanonicalName}}

    }
    Process{
        foreach ($id in $Users){
            $results += Get-ADUser -Filter {SAMAccountName -like $id} -Properties PasswordNeverExpires,LockedOut,PasswordLastSet,LastLogOnDate,CanonicalName | select $Headers 
        }
    }
    End{
        $results | ConvertTo-CSV -NoTypeInformation
    }
}

Get-ADUserInfo -Users

$Headers= contains a collection of calculate properties most of which are there the change the header. $Headers=包含一组计算属性,其中大部分是更改标头。 It does not need to be done this was and you could have just manually added a header line before the output of contents. 不需要这样做,您可以在输出内容之前手动添加标题行。 This solution however is more in line with what PowerShell is capable of. 但是,此解决方案更符合PowerShell的功能。

We collect all of the users in the array $results and in the End block convert that to CSV output which would not contain your custom headers. 我们收集数组$results中的所有用户,并在End块中将其转换为不包含您的自定义标头的CSV输出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM