当前位置:网站首页 > 更多 > 玩电脑 > 正文

[玩转系统] 清理 PowerShell 内容

作者:精品下载站 日期:2024-12-14 07:38:47 浏览:14 分类:玩电脑

清理 PowerShell 内容


[玩转系统] 清理 PowerShell 内容

get-content c:\work\computers.txt

潜在的问题是文本文件的格式可能不完美。您的文本文件可能有空行。或者您的计算机名可能有尾随空格。在 PowerShell 管道表达式中使用文本文件会使这些事情变得复杂。一种方法是使用Where-Object 过滤内容并简单地查找某些内容的存在。

get-content c:\work\computers.txt | where {$_} | <something else>

这对于过滤空白行效果很好。但如果您的一行中有人插入了制表符或按了几次空格键,则不会失败。因此,让我们更进一步,使用正则表达式来过滤掉任何不包含非空白字符的内容。

get-content c:\work\computers.txt | where {$_ -match "\w+"} | <something else>

这应该消除任何只有制表符或空格的行。当然,仍然存在前导空格或尾随空格的问题。但我们可以使用字符串对象的 Trim() 方法来处理这个问题。

这开始变得复杂了。因此,我编写了一个过滤函数来清理文本文件中的内容。

#requires -version 2.0

Filter Scrub {
<#
.Synopsis
Clean input strings
.Description
This command is designed to take string input and scrub the data, filtering
out blank lines and removing leading and trailing spaces. The default behavior
is to write the object to the pipeline, however you can use -PropertyName to
add a property name value. If you use this parameter, the assumption is that
contents of the text file are a single item like a computer name.
.Example
PS C:\> get-content c:\work\computers.txt | scrub | foreach { get-wmiobject win32_operatingsystem -comp $_}
.Example
PS C:\> get-content c:\work\computers.txt | scrub -PropertyName computername | test-connection 
#>

[cmdletbinding()]
Param(
[Parameter(Position=0,ValueFromPipeline=$True)]
[string[]]$InputObject,
[string]$PropertyName
)

  #filter out blank lines
  $InputObject | where {$_ -match "\w+"} | 
  ForEach-Object { 
    #trim off trailing and leading spaces
    $clean = $_.Trim()
    if ($PropertyName) {
        #create a customobject property
        New-Object -TypeName PSObject -Property @{$PropertyName=$clean}
    }
    else {
        #write the clean object to the pipeline
        $clean
    }
    } #foreach 

} #close Scrub

我们不再使用 Filter 关键字,但它似乎很合适,因为这是 Scrub 唯一做的事情。事实上,我故意没有使用传统的动名词名称。从技术上讲,这是一个高级功能,这只是一个进程脚本块。我编写它的假设是您将从 Get-Content 中获取字符串。

每个处理过的字符串都会被过滤以去除空格和空格。然后每个字符串都被修剪掉前导和尾随空格,最后写入管道。现在我可以运行命令行:

get-content c:\scripts\computers.txt | scrub

[玩转系统] 清理 PowerShell 内容

在我的最初版本中,这解决了我与文本文件有关的所有潜在问题。但后来我意识到我有机会再添加一项擦洗功能。许多 cmdlet 都具有按属性名称获取管道输入的参数。但文本文件中的字符串缺少属性名称。因此,我向 Scrub 过滤器添加了一个参数来添加属性名称。

get-content c:\scripts\computers.txt | scrub -PropertyName Computername

现在我正在向管道写入一个对象,并且可以利用管道绑定。

get-content c:\scripts\computers.txt | scrub -PropertyName Computername | test-connection -Count 1 

[玩转系统] 清理 PowerShell 内容

我不了解你,但这会非常方便。我希望你能让我知道你的想法。

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯