PowerShell 从表格\CSV 传递数值

huangapple go评论126阅读模式
英文:

PowerShell pass values from table\csv

问题

我正在尝试捕获3个设备x、y和z的详细信息。

要捕获x的详细信息,我必须使用以下详细信息运行脚本。

执行 script.ps1 x, x1, x2

x 是设备名称
x1 是资源组
x2 是订阅

表\csv 中有以下详细信息

x, x1, x2
y, y1, y2
z, z1, z2

我如何从x循环到z并传递它们对应的参数从表中。

通常,我会像下面这样获取详细信息

$servers = import-csv 'C:\arun.servers.csv';

foreach ($server in $servers)

{
..
}

但在这种情况下,我还需要从csv中为$server获取多个参数。

谢谢,
Arun

英文:

I am trying to capture details of 3 devices x,y,and z.

To capture details of x. i have to run the script with below details.

exec script.ps1 x,x1,x2

x is device name
x1 is resource group
x2 is subscription

Table\csv has below details

x,x1,x2
y,y1,y2
z,z1,z2

How to i loop from x to z and pass their corresponding parameters from the table.

Normally i fetch the details like below

$servers = import-csv 'C:\arun.servers.csv'

foreach ($server in $servers)

{
..
}

But in this case i need to also get multiple parameters from the csv for $server.

Thanks,
Arun

答案1

得分: 0

<!-- language-all: sh -->

[`Import-Csv`](https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/import-csv) 输出 [`[pscustomobject]`](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_PSCustomObject) 实例,每个实例代表一个 CSV 数据行。这些实例具有与 CSV 文件的列对应的属性(其名称从标题行获取),它们的值是给定数据行的字段值。

因此,在您的 `foreach` 循环中,您只需在每次迭代中访问感兴趣的属性,对应于给定数据行的列值。

以下假设列名为 `Device`、`Group` 和 `Subscription` - 根据需要进行调整。
如果您的 CSV 文件没有标题行,可以通过 `Import-Csv` 的 `-Header` 参数提供所需的列名。

foreach ($server in Import-Csv C:\arun.servers.csv) {

注意:我假设您需要分别传递值(以空格分隔)

而不是作为单个数组(用逗号分隔)

.\script.ps1 $server.Device $server.Group $server.Subscription
}

英文:

<!-- language-all: sh -->

Import-Csv outputs [pscustomobject] instances, each representing a CSV data row. These instances have properties named for the CSV file's columns (whose names are gleaned from the header row), and their values are the given data row's field values.

Therefore, in your foreach loop, you simply access the properties of interest in each iteration, corresponding to the given data row's column values.

The following assumes column names Device, Group, and Subscription - adjust as needed.
Should your CSV file lack a header row, supply the column names of choice via Import-Csv's -Header parameter.

foreach ($server in Import-Csv C:\arun.servers.csv) {
  # Note: I&#39;m assuming you need to pass the values *separately* (space-separated)
  #       not as a *single array* (&quot;,&quot;-separated)
  .\script.ps1 $server.Device $server.Group $server.Subscription
}

huangapple
  • 本文由 发表于 2023年3月7日 21:28:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/75662601.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定