繁体   English   中英

Powershell脚本循环输出到txt文件

[英]Powershell Script loop output to txt file

我正在使用Powershell脚本写入文本文件。 一位客户向我展示了此Powershell脚本,用于替换我以前使用的excel宏...

$computers= gc "C:\Users\Powershell\DeviceList.txt"
foreach ($computername in $computers)
{
write-output "<$computername>
      active = yes
      group = 
      interval = 5min
      name = $computername
      host = $computername
      community = 
      version = 1
      timeout = 0
      retries = default
      port = 161
      qos_source = 1
</$computername>"  | Out-File -filepath "C:\Users\Powershell\Cisco_Mon.txt" -append
}

它很好用,但是现在我想在它的基础上添加其他变量。 在一个理想的世界中,我希望它从excel扩展读取,以获取每行数据并将每列定义为一个变量。 现在使用另一个文本文件也可以。 这是我开始的内容(无效),但是您可以看到我的使用方向...

$computers= gc "C:\Users\Powershell\devicelist.txt"
$groups= gc "C:\Users\Powershell\grouplist.txt"
foreach ($computername in $computers) + ($groupname in $groups)
{
write-output "<$computername>
      active = yes
      group = $groupname
      interval = 5min
      name = $computername
      host = $computername
      community = 
      version = 1
      timeout = 0
      retries = default
      port = 161
      qos_source = 1
</$computername>"  | Out-File -filepath "C:\Users\Powershell\Cisco_Mon.txt" -append
}

当然不行了。 从本质上讲,如果我可以将上述每个选项定义为来自Excel电子表格的变量,例如$ community,$ interval,$ active等,我都会喜欢它。

任何帮助将不胜感激。 如果有人可以告诉我如何使用excel电子表格,请将每一列定义为一个变量,然后将上面的文本与变量一起写,那就太好了!!!

谢谢,

smt1228@gmail.com

下面是一个例子。

Excel数据:(用“ |”分隔的列

IP | String | Group
10.1.2.3 | Public | Payless

所需输出:

<10.1.2.3>
      active = yes
      group = Payless
      interval = 5min
      name = 10.1.2.3   
      host = 10.1.2.3   
      community = 
      version = 1
      timeout = 0
      retries = default
      port = 161
      qos_source = 1
</10.1.2.3>

加成:

从CSV中提取IP,字符串,组的数据,其中CSV中的数据如下...

10.1.2.3,public,group1
10.2.2.3,default,group2
10.3.2.3,public,group3
10.4.2.3,default,group4

被写成一个.txt文件

IP = 10.1.2.3.
String = public
Group = Group1

并在CSV中查找每一行

好,现在有新答案。 最简单的方法是将Excel文档另存为CSV,以使它看起来像这样(即与上面显示数据的方式非常相似):

IP,String,Group
10.1.2.3,Public,Payless

您仍然仍然可以在Excel中打开它(并且避免使用Office互操作程序尝试解析值)。

PowerShell可以很好地解析CSV:使用Import-Csv

Import-Csv grouplist.csv | ForEach-Object {
  "<{0}>
    active = yes
    group = {1}
    interval = 5min
    name = 10.1.2.3   
    host = 10.1.2.3   
    community = 
    version = 1
    timeout = 0
    retries = default
    port = 161
    qos_source = 1
  </{0}>" -f $_.IP, $_.Group
}

我在这里使用格式字符串,其中{0}等是占位符。 然后, -f是格式运算符,它在左侧使用格式字符串,在右侧使用占位符的参数。 您还可以看到,借助Import-Csv,您可以按名称访问各个列。

暂无
暂无

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

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