简体   繁体   English

Powershell-将文本文件的字符串拆分为多个块,然后去除不需要的信息

[英]Powershell - Split strings of text file into chunks, then strip out unwanted info

Working with Active Directory export script. 使用Active Directory导出脚本。 Currently, the script easily exports user objects from a given group into a .txt file as fully qualified names (ie. instead of reporting as "username", you get the ugly "CN=username,OU=foo,OU=bar,DC=foo,DC=bar"). 当前,脚本可以轻松地将给定组中的用户对象作为完全限定的名称导出到.txt文件中(即,您不会看到“ CN = username,OU = foo,OU = bar,DC = FOO,DC =栏“)。

My Powershell experience is novice at best. 我的Powershell经验充其量是新手。 What I've gotten so far: 到目前为止,我得到的是:

  • load contents of text file 加载文本文件的内容
  • split contents of text file at the "," 在“,”处分割文本文件的内容
  • write these contents into a second text file. 将这些内容写入第二个文本文件。

  • resulting text file looks like this: 生成的文本文件如下所示:

     "CN=username OU=foo OU=bar DC=foo DC=bar" 

My goal: 我的目标:

  • Save any resulting line of text that begins with "CN= (yes I'd like to keep that " at the beginning) 保存所有以“ CN =”开头的文本行(是的,我想在开头保留该行)
  • Delete everything else 删除其他所有内容
  • Strip "CN= from the beginning of the resulting lines 从结果行的开头删除“ CN =”
  • Note: usernames vary in length 注意:用户名长度不同

What I have so far: 到目前为止,我有:

$a = (Get-Content c:\test.txt | foreach-Object {$_.split(",,") })  
Out-File c:\results.txt -inputObject $a

I'm completely lost as to how to search text files for a pattern with a wildcard (ie. seach for any lines that contain "CN=* and keep those lines and those lines only) and then stick the results into a .txt. 我完全不知道如何使用通配符在模式中搜索文本文件(例如,搜寻包含“ CN = *”的行并仅保留这些行和仅那些行),然后将结果粘贴到.txt中。

Thank you so much for any and all guidance you might provide. 非常感谢您提供的所有指导。

Select-String would allow that. Select-String将允许这样做。 It's kinda grep for PowerShell. 这是PowerShell的grep

However, if I understand you correctly you can do that a bit easier with 但是,如果我对您的理解正确,则可以使用

$a = (Get-Content c:\test.txt | foreach-Object {$_.split(",,") }) -match '^CN='

The comparison operators can be applied to a list of objects and return only the matching items. 可以将比较运算符应用于对象列表,并且仅返回匹配项。

Perhaps also take a look at the Quest AD cmdlets and use that as your export script. 也许还要看看Quest AD cmdlet,并将其用作导出脚本。 That way you can choose exactly which attributes you want without having to filter the output of a text file eg 这样,您可以精确选择所需的属性,而不必过滤文本文件的输出,例如

Get-QADUser -Searchroot foo.bar/MyOu | Select Name, DisplayName, email 

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

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