PowerShell中把Here-String转换数组对象的小技巧

你或许知道PowerShell中的Here-String特性,我们很多时候都会把一些未经处理的非格式化数据放入Here-String中。正如文章的标题所言,今天我们要把Here-String里的数据转换为数组数据。

比如,我手中一串数据,这其中时一长串的各种计算机名:

$computers = @"
Computer1   
Computer2
Computer3
Computer4
Computer5
Computer6
Computer7
Computer8
"@ 
我们需要去读取这个变量computers里的值,可是单纯的循环遍历肯定是不行的,就像下面这样:

$computers = @"
Computer1   
Computer2
Computer3
Computer4
Computer5
Computer6
Computer7
Computer8
"@ 

foreach($cn in $computers)
{
    $cn+"-sh"
}
我们在循环遍历里想给每个计算机名后缀添加上"-sh"字符,大师得到了如下结果,因为它是一整块数据,并不是一个个数组元素:

Computer1   
Computer2
Computer3
Computer4
Computer5
Computer6
Computer7
Computer8-sh
那么我们必须想办法把这块数据分割成一个个数据也就是我们所要的数组元素,如下我使用了这个方法:

$computers = @"
Computer1   
Computer2
Computer3
Computer4
Computer5
Computer6
Computer7
Computer8
"@ 

$newComputers = ($computers -split "`n")
这里我们用split参数配合"`n"来告诉PowerShell我们打算以回车为分隔来识别每一条数据,现在我们再来用GetType()方法看看,它已经是一个标准的数组对象了:

IsPublic IsSerial Name                                     BaseType                                                                                                                            
-------- -------- ----                                     --------                                                                                                                            
True     True     String[]                                 System.Array  
再次运行修改过的方法,我们得到正确的内容了:

$computers = @"
Computer1   
Computer2
Computer3
Computer4
Computer5
Computer6
Computer7
Computer8
"@ 

$newComputers = ($computers -split "\n")

foreach($cn in $newComputers)
{
    $cn+"-sh"
}
结果如下:

Computer1-sh
Computer2-sh
Computer3-sh
Computer4-sh
Computer5-sh
Computer6-sh
Computer7-sh
Computer8-sh



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值