简体   繁体   English

PowerShell外文件操作

[英]PowerShell Out-file manipulation

i hope someone can help. 我希望有人能帮帮忙。 I am trying to manipulate a file created by powershell. 我正在尝试处理Powershell创建的文件。 I managed to get to the end result that i want, but i am sure it would be easier if it was only one command. 我设法达到了想要的最终结果,但是我敢肯定,如果只是一个命令,它将更加容易。

# Invoke the Exchange Snapping ( make sure you are Exchange Admin to do it SO)
add-pssnapin Microsoft.Exchange.Management.PowerShell.E2010

#Create a file with list of DL in the organization
Get-DistributionGroup | Select-Object Name | Out-File C:\Pre_DLGroups.txt
$content = Get-Content C:\Pre_DLGroups.txt

#Remove the 3 first lines of the file that you dont need it
$content | Select-Object -Skip 3 | Out-file C:\DLGroups.txt

#Trim the space in the end and crate the Final file
Get-Content C:\DLGroups.txt | Foreach {$_.TrimEnd()} | Set-Content c:\FinalDLGroup.txt

is that way to make the end result in a single file rather than creating 3? 是将最终结果保存在一个文件中,而不是创建3个文件吗? cheers 干杯

Elton 埃尔顿

You can send your content across the pipeline without writing it out to files. 您可以跨管道发送内容,而无需将其写出到文件中。 You can use parenthesis to group the output of certain sets of cmdlets and/or functions, and then pipe that output through to the intended cmdlets. 您可以使用括号对某些cmdlet和/或函数集的输出进行分组,然后通过管道将其输出到所需的cmdlet。

This can all be applied on a single line, but I've written it here on multiple lines for formatting reasons. 所有这些都可以在一行上应用,但是出于格式化的原因,我在这里将其写在了多行上。 The addition of Out-String is something of a safety measure to ensure that whatever output you're intending to trim can actually be trimmed. 为了确保实际要修剪的任何输出都可以被修剪,增加Out-String是一项安全措施。

Since we're not getting this content from a text file anymore, powershell could possibly return an object that doesn't understand TrimEnd() , so we need to be ready for that. 由于我们不再从文本文件中获取此内容,因此powershell可能会返回一个不了解TrimEnd()的对象,因此我们需要为此做好准备。

(Get-DistributionGroup | Select-Object Name) | 
Out-String | 
Select-Object -Skip 3 |
Foreach {$_.TrimEnd()} | 
Set-Content c:\FinalDLGroup.txt

However, an even smaller solution would involve just pulling each name and manipulating it directly. 但是,一个更小的解决方案将涉及仅提取每个名称并直接对其进行操作。 I'm using % here as an alias for Foreach-Object . 我在这里使用%作为Foreach-Object的别名。 This example uses Get-ChildItem , where I have some files named test in my current directory: 此示例使用Get-ChildItem ,其中在当前目录中有一些名为test的文件:

(Get-ChildItem test*) | 
% { $_.Name.TrimEnd() } | 
Set-Content c:\output.txt
Get-DistributionGroup | 
Select-Object -ExpandProperty Name -Skip 3 |
Set-Content c:\FinalDLGroup.txt

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

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