14

我想用自定义字符串在数据集中附加几个字符串。

例子

数据集内容:

Test1
Test2
Test3

附加后的结果:

Test1.com
Test2.com
Test3.com

我是否必须使用正则表达式解析到每个 Test[n] 的末尾才能附加自定义字符串(.com)?有没有人有一个确切描述如何做到这一点的例子?

我正在从 SQL 表中读取数据并将值写入数据集,该数据集通过以下方式导出到 CSV:

$DataSet.Tables[0] | ConvertTO-Csv -Delimiter ',' -NotypeInformation |`% { $_ -replace '"','' } |  out-file  $outfile -Encoding "unicode"

DataSet 包含字符串,例如:

Banana01
Banana02
Apple01
Cherry01
Cherry02
Cherry03

我想做的事情是.com只附加到Cherry01,Cherry02Cherry03, 并在附加后.com, 将其导出为 CSV 文件。

4

3 回答 3

21

有很多方法。这里有几个:

# Using string concatenation
'Test1','Test2','Test3' | Foreach-Object{ $_ + '.com' }

# Using string expansion
'Test1','Test2','Test3' | Foreach-Object{ "$_.com" }

# Using string format
'Test1','Test2','Test3' | Foreach-Object{ "{0}{1}" -f $_,'.com' }
于 2012-07-25T12:22:46.927 回答
9

你可以使用这样的东西:

示例 1

$t = "test"
$t = $t + ".com"

示例 2

$test = @("test1","test2")

$test | ForEach-Object {
$t = $_ + ".com"
Write-Host $t}

使用您添加的代码,我做到了这一点。我没有数据库来测试它,所以我手动创建了数据集,所以您可能只需将代码中的$DataSet[0]更改为$DataSet.Tables[0]

$DataSet[0] | ConvertTO-Csv -Delimiter ',' -NotypeInformation  | Foreach-Object{$T=$_
IF($T -match "(Cherry\d\d)"){$T = $T -replace "(Cherry\d\d)(.+)",'$1.com$2'};$T } |  out-file  $outfile -Encoding "unicode"
于 2012-07-25T12:00:24.657 回答
0

$array | %{if($_ -match "^Cherry\d\d"){$_ += ".com"};$_}

于 2012-07-25T14:38:52.527 回答