Powershell脚本循环输出到txt文件

我正在使用Powershell脚本来写入文本文件。 一个客户端向我展示了这个Powershell脚本来replace我以前使用的一个excelmacros…

$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 } 

它工作的很好,但现在我想build立它添加额外的variables。 在一个完美的世界中,我希望它能够从excel中读取每行数据,并将每列定义为一个variables。 现在使用另一个文本文件也很好。 这是我开始的(它不工作),但你可以看到我要去的地方…

 $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电子表格的variables,如$社区,$间隔,$活跃等

任何帮助,这将是非常appreaciated。 如果有人能告诉我如何使用excel电子表格,将每一列定义为一个variables,并用variables写上面的文本,那将是很棒的!!!

谢谢,

smt1228@gmail.com

这将是一个例子如下…

Excel数据:( Colums与“|”分隔

 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中提取数据,CSV,string,组数据如下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互操作来尝试parsing这些值)。

PowerShell可以parsingCSV就好了:使用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 } 

我在这里使用格式string{0}等是占位符。 -f然后是格式运算符,其左侧的格式string和右侧的占位符参数。 你也可以看到你可以通过他们的名字访问各个列,这要感谢Import-Csv。