2011-07-26 47 views
2

所以我目前有一组csv文件,我梳理并替换使用powershell的各个部分。但是,目前我使用的流程时间密集,我想知道是否有更好的更简化的解决方案。简化基于Powershell的文件版本

当前码:(这是所有包含在每个循环中,其中$文件是文件位置和$结核病是一种表的名称)

Invoke-sqlcmd -query "select Distinct * from $($tb.name) WITH (NoLock)" -server server -database database | Export-CSV $file -Delimiter "|" -Encoding "Unicode" -NoTypeInformation 
(get-content $file) -replace '"?\|"?', "|" | out-file $file 
(get-content $file) -replace '\|true\|', '|1|' | out-file $file 
(get-content $file) -replace '\|false\|', '|0|' | out-file $file 
(get-content $file) -replace '^"' | out-file $file 
(get-content $file) -replace '"$' | out-file $file 
(get-content $file) -replace '^true\|', '1|' | out-file $file 
(get-content $file) -replace '^false\|', '0|' | out-file $file 
(get-content $file) -replace 'true$', '1' | out-file $file 
(get-content $file) -replace 'false$', '0' | select -Skip 1 | out-file $file 
(get-content $file) -replace '\|false\|', '|0|' | out-file $file 
} 

回答

4

Upvoted答案由@EBGreen,这可能是解决方案。只是为了显示你如何做到这一点(和如何连锁经营),我会添加代码:

Invoke-SqlCmd... 
(get-content $file) -replace '"?\|"?', "|" ` 
        -replace '\|true\|', '|1|'` 
... 
        -replace '\|false\|', '|0|' | out-file $file 

除此之外考虑取代了原先将数据导出为CSV之前。您可以从Invoke-SqlCmd开始收集并更换适当的属性值。 另外考虑如果简单地将true替换为1false而使用0将删除大部分正则表达式。

+0

+1 - 我喜欢把所有的替换操作像我在示例中那样分开,因为我的大脑以这种方式工作,但是你的确没有那么冗长,并且功能上应该提供相同的资源节约。 – EBGreen

3

首先和最明显的事情,我看到的是,您将文件从磁盘加载并写回每个替换。我将首先进行的优化是将文件加载到内存中,然后将其全部替换到内存中,然后将其写回到磁盘。

喜欢的东西:

$contents = (get-content $file) -replace '"?\|"?', "|" 
$contents = $contents -replace '\|true\|', '|1|' 
e 
t 
c 
. 
. 
. 
$contents | out-file $file 
+0

我喜欢这个想法,你知道这种机动的语法吗?据我所知,我只能取代每个获取内容周期的一组数据?我可以不断地管它吗? – Jerome

+0

好吧,我会试试看,谢谢你,非常感谢。 – Jerome