使用PowerShell搜索CSV

时间:2017-07-13 11:57:10

标签: powershell csv scripting powershell-v2.0 export-to-csv

我正在尝试使用PowerShell执行简单的CSV任务,但它对我来说真的不起作用。

我有这样的CSV文件。

Name    LineUri                     Status         BusinessUnit Location
Test 1  tel:+61396176100;ext=6100   Spare          Sales        VIC
Test 2  tel:+61396176101;ext=6101   Spare          Sales        VIC
Test 2  tel:+61396176102;ext=6102   Spare          Support      NSW
Test 2  tel:+61396176103;ext=6103   Used           WareHouse    SA
Test 2  tel:+61396176104;ext=6104   Used           Sales        SA
Test 2  tel:+61396176105;ext=6105   Spare          Support      VIC
Test 2  tel:+61396176106;ext=6106   Spare          WareHouse    VIC
Test 2  tel:+61396176107;ext=6107   Spare          Support      VIC

我正在尝试根据位置搜索状态为“Spare”的LineUri。

所以标准是这样的:

Status = "Spare" 
BusinessUnit = "WareHouse"
Location = "VIC"

这应该给我“tel:+61396176106; ext = 6106”作为备用。

一旦我有了备用LineUri,我就会执行另一个逻辑,然后将该特定LineUri的状态更改为“已使用”。

我有这个代码给了我lineUri,但我不知道如何从ForEach-Object循环中取出返回值并在另一个函数中使用。

$path     = Split-Path -parent $MyInvocation.MyCommand.Definition
$newpath  = $path + "\PhoneData.csv"
# Array of spare numbers that meet your criteria
$firstAvailableSpare

# criteria
$currentStatus = "Spare"
$userBusinessUnit = "WareHouse"
$userLocation = "VIC"

$csv = Import-Csv $newpath -Delimiter ","

$csv | ForEach-Object {
    $Status += $_.Status
    $BusinessUnit += $_.BusinessUnit
    $Location += $_.Location

    if (($_.Status -eq $currentStatus) -and ($_.BusinessUnit -eq $userBusinessUnit) -and ($_.Location -eq $userLocation)) { 
        $firstAvailableSpare = $_ # Assign the first
        break # break the loop so we don't get additional hits
    }
}

try {
    #use the return value and update the csv so that its status is changed to Used
} catch {
    #do something else if failed
}

1 个答案:

答案 0 :(得分:2)

使用Where-Object过滤器根据多个字段从CSV中选择行,并使用Select-Object来限制结果。

$firstAvailableSpare = $csv | Where-Object {
    $_.Status -eq $currentStatus -and
    $_.BusinessUnit -eq $userBusinessUnit -and
    $_.Location -eq $userLocation
} | Select-Object -Expand LineUri -First 1

您可以使用该LineUri修改行:

foreach ($row in $csv) {
    if ($row.LineUri -eq $firstAvailableSpare) {
        $row.Status = 'Used'
    }
}