Powershell不会拆分函数返回的字符串

时间:2016-11-17 17:24:13

标签: windows powershell

我正在尝试导入一个CSV,其中包含虚构的地方和一周中每个小时的虚构地点。

小时为5:00-4:00格式。有些人有空位。我创建了一个删除空格的函数。运行该函数后,PowerShell无法对返回的字符串(即-split)执行任何进一步的操作。

CSV:

Node,SAT,SUN,MON,TUE,WED,THU,FRI
PizzaPlace,9:00 – 4:30,0,8:00-3:30,7:00 – 10:00,10:00 – 4:00,10:00 – 4:00,10:00 – 4:00
BigPharma,0,5:00 – 4:00,7:00-6:00,7:00-6:00,0,0,7:00-6:00
GreenHouse,12:00-8:00,0,12:00-7:30,12:00-7:30,12:00-7:30,12:00-7:30,12:00-7:30
Portapoty,12:00-8:00,Closed,10:00-6:00,10:00-7:30,10:00-6:00,10:00-7:30,10:00-6:00

PS1脚本:

function Unk-AMPM ($openStr) {
    $openStr -replace " ";
}

$csvInputs = Import-CSV SampHours.csv;

$srPRBN = "Our hours for";
$srPRAN = "are";

$dsWed = "Wednesday";

foreach ($csvLine in $csvInputs) {

    $retailer = $csvLine.Node;

    [string] $openWed = Unk-AMPM $csvLine.WED;

    Write-Host "Value of openWed before split: "$openWed;

    $openWedA = $openWed -split "-";

    Write-Host "Value of openWedA[0]: "$openWedA[0];
    Write-Host "Value of openWedA[1]: "$openWedA[1];

    if ($openWedA[0] -eq 0 -or $openWedA[0] -eq 'Closed') {
        $ohsWed = "closed";
    } else { $ohsWed = $openWedA[0] + " to " + $openWedA[1]; }

    Write-Host $srPRBN $retailer $srPRAN $ohsWed "on" $dsWed;

}

结果:

Value of openWed before split:  10:00–4:00
Value of openWedA[0]:  10:00–4:00
Value of openWedA[1]:  
Our hours for PizzaPlace are 10:00–4:00 to  on Wednesday

Value of openWed before split:  0
Value of openWedA[0]:  0
Value of openWedA[1]:  
Our hours for BigPharma are closed on Wednesday

Value of openWed before split:  12:00-7:30
Value of openWedA[0]:  12:00
Value of openWedA[1]:  7:30
Our hours for GreenHouse are 12:00 to 7:30 on Wednesday

Value of openWed before split:  10:00-6:00
Value of openWedA[0]:  10:00
Value of openWedA[1]:  6:00
Our hours for Portapoty are 10:00 to 6:00 on Wednesday

1 个答案:

答案 0 :(得分:4)

包含空格的条目中的不是连字符(U+002D),而是破折号U+2013

如果数据是从具有“自动”格式的文本处理器复制的(例如Word),通常会看到这一点。

使用“标点,破折号”unicode类别来匹配和拆分这两种类型:

$openStr -split '\p{Pd}'