Powershell 脚本从 .csv 文件读取 2 列数据

标签 powershell

我正在尝试编写一个 PowerShell 脚本来获取 csv 文件的 2 列:

ProductName          ProductCode
-----------------------------------------------------------
Java 7 Update 67     {26374892-xxxx-xxxx-xxxx-123456789012}
Java 8  Update 25    {26374892-xxxx-xxxx-xxxx-902341562789}

我只想获取要在 foreach 循环中使用的 ProductCode 列值。

我尝试了以下方式

$code1 = Get-Contect %path% | Foreach-Object {
    $_ -split '\s+' | Select-object -skip 1 | Select-Object -Last 1
} 

foreach($code in $code1){ write-host $code } 

我的输出低于

67,{232424-55567-8879-xxxxxxx} 
25,{324356456-5674-xxxx-xxxxxx}

但我只想输出产品代码,例如

{3245345345-3454-56656757-xxxxx}

最佳答案

这看起来并不像 CSV。我想说最简单的方法是这样的:

Get-Content %path% | Foreach-Object { $_ -split '\s+' | Select-Object -Last 1 }

这样您将在将字符串拆分为多个空格后获得最后一个对象

ps。如果您需要跳过标题,您可以添加 |在获取内容之后选择对象 -Skip 1
pps。如果 import-csv 允许在 delimiter 中使用正则表达式 import csv 会更容易使用,但我怀疑它是否允许这样做。 点赞。对我有用:

> cat .\Untitled-2.txt
ProductName ProductCode
Java 7 Update 67     {26374892-xxxx-xxxx-xxxx-123456789012}
Java 8  Update 25    {26374892-xxxx-xxxx-xxxx-902341562789}
> Get-Content .\Untitled-2.txt | select-object -skip 1 | Foreach-Object { $_ -split '\s+' | Select-Object -Last 1 }
{26374892-xxxx-xxxx-xxxx-123456789012}
{26374892-xxxx-xxxx-xxxx-902341562789}

关于Powershell 脚本从 .csv 文件读取 2 列数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51151567/

相关文章:

powershell - 如何在Powershell脚本中一个接一个地运行多个脚本

powershell - 有没有办法抑制 Write-Error cmdlet 的 "extra"输出?

powershell - 尝试连接到目标计算机时 VSTS AzureFileCopy 权限被拒绝

PowerShell 脚本仅导出没有文件扩展名的文件名列表,然后输出到每个目录单独的文本文件

iis - 如何使用 PowerShell 脚本远程启动/停止 IIS 6.0/7.0?

.net - 当PowerShell溢出时,如何使PowerShell捕获日志文件?

powershell - 按子文件夹列出文件计数

powershell - PowerShell别名分配工厂

PowerShell:ForEach-Object with InputObject 有什么意义?

powershell - PSExec:cmd 在 [COMPUTER] 上退出,错误代码为 -196608