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

[玩转系统] 将字符串转换为 PowerShell 属性名称

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

将字符串转换为 PowerShell 属性名称


[玩转系统] 将字符串转换为 PowerShell 属性名称

例如,我可以很容易地将 ARP.EXE 命令的输出转换为对象。这就是我的开始。

[玩转系统] 将字符串转换为 PowerShell 属性名称

我想做的就是获取列标题并将它们转换为属性。问题是我不喜欢属性名称中的空格。另外,我需要提前知道命令行标题,这样我就可以使用自定义哈希表之类的东西来重命名。我想要一些更方便的东西,并且可以与几乎任何命令行输出一起使用,尽管我认为表格输出效果最好。因此我想出了一个简短的函数,我称之为 Convert-StringProperty。

Function Convert-StringProperty {

<#
.Synopsis
Convert strings to proper case property names.
.Description
This function will take strings like principal_id and convert it into a form
more suitable for a property name, ie PrincipalID. If the text doesn't contain
the delimiter, which by default is a single space, then the first character will
be set to upper case. Otherwise, the string is is split on the delimiter, each
first character is set to upper case and then everything joined back together.

.Example
PS C:\> Convert-StringProperty principal_id
PrincipalId
.Example
PS C:\> $raw = arp -g | select -Skip 2

This command will get ARP data. It can then be processed using this function:

PS C:\> [regex]$rx="\s{2,}"
PS C:\> $properties = $rx.Split($raw[0].trim()) | Convert-StringProperty  
PS C:\> for ($i=1;$i -lt $raw.count; $i++) {
  $splitData = $rx.split($raw[$i].Trim())
  #create an object for each entry
  $hash = [ordered]@{}
  for ($j=0;$j -lt $properties.count;$j++) {
    $hash.Add($properties[$j],$splitData[$j])
  } 
  [pscustomobject]$hash
}

InternetAddress                     PhysicalAddress                        Type                                       
---------------                     ---------------                        ----                                       
172.16.10.1                         00-13-d3-66-50-4b                      dynamic                                    
172.16.10.100                       00-0d-a2-01-07-5d                      dynamic                                    
172.16.10.101                       2c-76-8a-3d-11-30                      dynamic                                    
172.16.10.199                       00-0a-cd-25-28-99                      dynamic                                    
172.16.10.254                       20-4e-7f-b5-0f-1a                      dynamic                                    
172.16.100.1                        c4-3d-c7-48-16-ee                      dynamic                                    
172.16.255.255                      ff-ff-ff-ff-ff-ff                      static                                     
224.0.0.22                          01-00-5e-00-00-16                      static                                     
224.0.0.251                         01-00-5e-00-00-fb                      static                                     
224.0.0.252                         01-00-5e-00-00-fc                      static                                     
239.255.255.250                     01-00-5e-7f-ff-fa                      static                                     
255.255.255.255                     ff-ff-ff-ff-ff-ff                      static
.Notes
Last Updated: 3/27/2014
Version     : 0.9.6

Learn more:
 PowerShell in Depth: An Administrator's Guide
 PowerShell Deep Dives 
 Learn PowerShell 3 in a Month of Lunches 
 Learn PowerShell Toolmaking in a Month of Lunches 

   ****************************************************************
   * DO NOT USE IN A PRODUCTION ENVIRONMENT UNTIL YOU HAVE TESTED *
   * THOROUGHLY IN A LAB ENVIRONMENT. USE AT YOUR OWN RISK.  IF   *
   * YOU DO NOT UNDERSTAND WHAT THIS SCRIPT DOES OR HOW IT WORKS, *
   * DO NOT USE IT OUTSIDE OF A SECURE, TEST SETTING.             *
   ****************************************************************

.Link
https://jdhitsolutions.com/blog/2014/03/convert-a-string-to-a-powershell-property-name
#>

[cmdletbinding()]
Param(
[Parameter(Position=0,Mandatory=$True,
HelpMessage="Enter a string to convert",
ValueFromPipeline=$True,
ValueFromPipelineByPropertyName=$True)]
[ValidateNotNullorEmpty()]
[Alias("name")]
[string]$Text,

[ValidateNotNullorEmpty()]
[string]$Delimiter = " "

)

Begin {
    Write-Verbose -Message "Starting $($MyInvocation.Mycommand)"  
    Write-Verbose "Using delimiter: $Delimiter"

    #define a regular expression pattern
    [regex]$rx = "[^$Delimiter]+"

} #begin

Process {
    Write-Verbose "Converting $Text"
    #initialize the output string for the new property name
    [string]$Output=""

    #find each word
    $rx.Matches($text) | foreach {

      #capitalize the first letter of each word
      $value = "{0}{1}" -f $_.value[0].tostring().ToUpper(),$_.value.tostring().substring(1).ToLower()

      #and add to output stipping off any extra non word characters
      $output+=  $Value -replace "\W+",""

    } #foreach

    #send the new string to the pipeline
    $Output
    $counter++
} # process

End {
    Write-Verbose -Message "Ending $($MyInvocation.Mycommand)"
} #end

} #end function

这是它的工作原理。我将获取原始 ARP 输出并跳过前几行。

$raw = arp -g | select -Skip 2

$raw 变量包含我想要转换为对象的数据。

  
Internet Address      Physical Address      Type
  172.16.10.1           00-13-d3-66-50-4b     dynamic
  172.16.10.100         00-0d-a2-01-07-5d     dynamic
  172.16.10.101         2c-76-8a-3d-11-30     dynamic
  172.16.10.199         00-0a-cd-25-28-99     dynamic
  172.16.10.254         20-4e-7f-b5-0f-1a     dynamic
  172.16.30.212         94-de-80-84-8d-4d     dynamic
  172.16.100.1          c4-3d-c7-48-16-ee     dynamic
  172.16.255.255        ff-ff-ff-ff-ff-ff     static
  224.0.0.22            01-00-5e-00-00-16     static
  224.0.0.251           01-00-5e-00-00-fb     static
  224.0.0.252           01-00-5e-00-00-fc     static
  239.255.255.246       01-00-5e-7f-ff-f6     static
  239.255.255.250       01-00-5e-7f-ff-fa     static
  255.255.255.255       ff-ff-ff-ff-ff-ff     static

第一行包含属性名称,但我希望它们不带空格。作为函数之外的一个单独步骤,我需要拆分第一行。我将使用匹配 2 个或更多空格的正则表达式模式来实现此目的。

[regex]$rx="\s{2,}"
$properties = $rx.Split($raw[0].trim()) | Convert-StringProperty

我可以获取第一行项目 [0],删除前导和尾随空格并将其拆分。这将为我提供三个字符串:互联网地址、物理地址和类型。然后将它们中的每一个通过管道传输到我的 Convert-StringProperty。

该函数将查看每个字符串并根据分隔符再次分割它,默认情况下分隔符是空格。但是,如果您遇到诸如 INTERNET_ADDRESS 之类的 CLI 名称,您可以指定不同的内容。然后用大写的第一个字母处理每个单词。最终结果是驼峰式大小写,因此“Internet Address”变为“InternetAddress”。

一旦我知道我的属性名称是什么,我就可以继续解析命令行输出并创建一个自定义对象。

for ($i=1;$i -lt $raw.count; $i++) {
  $splitData = $rx.split($raw[$i].Trim())
  #create an object for each entry
  $hash = [ordered]@{}
  for ($j=0;$j -lt $properties.count;$j++) {
    $hash.Add($properties[$j],$splitData[$j])
  } 
  [pscustomobject]$hash
}

您仍然需要编写代码来处理命令行工具,但您可以使用此函数来定义正确的 PowerShell 属性。这里还有一个例子。

$raw = qprocess
$properties = $raw[0] -split "\s{2,}" | Convert-StringProperty
$raw | select -Skip 1 | foreach {
 #split each line
 $data = $_ -split "\s{2,}"
 $hash=[ordered]@{}
 for ($i=0;$i -lt $properties.count;$i++) {
   #strip off any non word characters
   $hash.Add($properties[$i],($data[$i] -replace '\W+',''))
 }
 [pscustomobject]$hash
}

这需要如下命令输出:

 USERNAME              SESSIONNAME         ID    PID  IMAGE
 jeff                  services             0   1920  sqlservr.exe
>jeff                  console              1   3312  taskhostex.exe
>jeff                  console              1   3320  ipoint.exe
>jeff                  console              1   3328  itype.exe

并将其转换为 PowerShell 输出,如下所示:

Username    : jeff
Sessionname : services
Id          : 0
Pid         : 1920
Image       : sqlservrexe

Username    : jeff
Sessionname : console
Id          : 1
Pid         : 3312
Image       : taskhostexexe

Username    : jeff
Sessionname : console
Id          : 1
Pid         : 3320
Image       : ipointexe

在另一篇文章中,我将与您分享另一个利用此功能的工具。享受。

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

取消回复欢迎 发表评论:

关灯