简体   繁体   English

导入-CSV 和 Foreach

[英]Import-CSV and Foreach

I've got a huge comma seperated CSV-list with IP-addresses of my network that I want to run queries against.我有一个巨大的逗号分隔的 CSV 列表,其中包含我想要对其运行查询的网络的 IP 地址。 Example of my CSV input:我的 CSV 输入示例:

172.168.0.1,172.168.0.2,172.168.0.3,172.168.0.4

Etc....等等....

When I run the following code to test for the output:当我运行以下代码来测试输出时:

$filepath = "c:\scripts\servers.csv" 
$servers = Import-CSV $filepath -delimiter "," 

Foreach ($server in $servers) {
     write-host $server

}

I get no output, I think it's because there are no headers specified.我没有输出,我认为这是因为没有指定标题。 I can obviously do a workaround and open the CSV-file and type in all the headers.我显然可以做一个解决方法并打开 CSV 文件并输入所有标题。 Are there any other ways to solve this?有没有其他方法可以解决这个问题?

You can create the headers on the fly (no need to specify delimiter when the delimiter is a comma):您可以即时创建标题(当分隔符为逗号时无需指定分隔符):

Import-CSV $filepath -Header IP1,IP2,IP3,IP4 | Foreach-Object{
   Write-Host $_.IP1
   Write-Host $_.IP2
   ...
}
$IP_Array = (Get-Content test2.csv)[0].split(",")
foreach ( $IP in $IP_Array){
    $IP
}

Get-content Filename returns an array of strings for each line. Get-content Filename 为每一行返回一个字符串数组。

On the first string only, I split it based on ",".仅在第一个字符串上,我根据“,”将其拆分。 Dumping it into $IP_Array.将其转储到 $IP_Array 中。

$IP_Array = (Get-Content test2.csv)[0].split(",")
foreach ( $IP in $IP_Array){
  if ($IP -eq "2.2.2.2") {
    Write-Host "Found $IP"
  }
}

Solution is to change Delimiter.解决方案是更改分隔符。

Content of the csv file -> Note .. Also space and , in value csv 文件的内容 -> 注释 .. 还有空格和 , 值

Values are 6 Dutch word aap,noot,mies,Piet, Gijs, Jan值为 6 个荷兰语单词 aap、noot、mies、Piet、Gijs、Jan

Col1;Col2;Col3

a,ap;noo,t;mi es

P,iet;G ,ijs;Ja ,n



$csv = Import-Csv C:\TejaCopy.csv -Delimiter ';' 

Answer:回答:

Write-Host $csv
@{Col1=a,ap; Col2=noo,t; Col3=mi es} @{Col1=P,iet; Col2=G ,ijs; Col3=Ja ,n}

It is possible to read a CSV file and use other Delimiter to separate each column.可以读取 CSV 文件并使用其他分隔符来分隔每一列。

It worked for my script :-)它适用于我的脚本:-)

$filepath = ".\\ADcomputerslist.csv" $servers = Import-CSV $filepath -delimiter "," $filepath = ".\\ADcomputerslist.csv" $servers = Import-CSV $filepath -delimiter ","

Foreach ($entry in $servers) { write-host $entry.name } Foreach ($servers 中的 $entry) { write-host $entry.name }

also can replace stupid file with object.也可以用对象替换愚蠢的文件。

$servers = Get-ADComputer -Filter * -Property * | $servers = Get-ADComputer -Filter * -Property * | Select-Object Name,OperatingSystem,OperatingSystemVersion,ipv4Address Select-Object Name,OperatingSystem,OperatingSystemVersion,ipv4Address

Foreach ($entry in $servers) { write-host $entry.name } Foreach ($servers 中的 $entry) { write-host $entry.name }

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

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