【问题标题】:Powershell - multiple commands to multiple filesPowershell - 多个文件的多个命令
【发布时间】:2018-08-10 07:21:22
【问题描述】:

希望有人能帮我完成这个脚本。我有一个文件夹,里面装满了需要修改的 *.imp(纯文本 - csv 导出)文件。这些文件会按计划更新,所以这个 Powershell 脚本也会按计划更新,但我似乎无法让它工作。

这是我到目前为止所达到的地方......

$InputFiles = Get-Item "C:\scripts\*.imp"
$OldString  = '@##'
$NewString  = '"'
$InputFiles | ForEach {
(Get-Content -Path $_.FullName).Replace($OldString,$NewString) | Set-Content -Path $_.FullName
(Get-Content -Path $_.FullName).-notmatch '(^[\s,-]*$)|(rows\s*affected)' | Set-Content -Path $_.FullName
(Get-Content -Path $_.FullName).-notmatch 'HeaderRow' | Set-Content -Path $_.FullName
}

如果我离开第一个 Get-Content 行,它可以工作,但添加其他两个则不行。 无论如何可以帮助我吗? 谢谢 卢克

【问题讨论】:

  • 删除.-notmatch中的点(替换为空格)

标签: powershell csv powershell-2.0


【解决方案1】:

正如 Lieven 指出的,您需要删除第二条和第三条语句中的 . 引用运算符:

$InputFiles = Get-Item "C:\scripts\*.imp"
$OldString  = '@##'
$NewString  = '"'
$InputFiles | ForEach {
  (Get-Content -Path $_.FullName).Replace($OldString,$NewString) | Set-Content -Path $_.FullName
  (Get-Content -Path $_.FullName) -notmatch '(^[\s,-]*$)|(rows\s*affected)' | Set-Content -Path $_.FullName
  (Get-Content -Path $_.FullName) -notmatch 'HeaderRow' | Set-Content -Path $_.FullName
}

您可以链接所有操作,而不是从磁盘读取和写入文件三次:

$InputFiles = Get-Item "C:\scripts\*.imp"
$OldString  = '@##'
$NewString  = '"'
$InputFiles | ForEach {
  (Get-Content -Path $_.FullName).Replace($OldString,$NewString) -notmatch '(^[\s,-]*$)|(rows\s*affected)' -notmatch 'HeaderRow' | Set-Content -Path $_.FullName
}

【讨论】:

  • 感谢 Lieven 和 Mathias。我使用了您提供给 Mathias 的更整洁的版本,效果非常好。感谢您的热心帮助!
猜你喜欢
  • 1970-01-01
  • 2018-04-26
  • 1970-01-01
  • 2020-04-06
  • 1970-01-01
  • 2020-11-02
  • 1970-01-01
  • 1970-01-01
  • 2011-10-21
相关资源
最近更新 更多