4

我无法在一个 Foreach 或 Foreach-Object 循环中使用多个命令

我的情况是——

  1. 我有很多文本文件,大约 100 个。所以它们被阅读Get-ChildItem $FilePath -Include *.txt
  2. 每个文件的结构都是相同的,只是关键信息不同。例子

    用户:Somerandomname

    计算机:Somerandomcomputer

使用-Replace命令我删除“用户:”和“计算机:”所以$User = Somerandomname$computer = "Somerandomcomputer。在每个圈子中,$user 和 $Computer 和 -Append 应该被写入一个文件。然后应该读取下一个文件。

foreach-object { $file = $_.fullname;

应该使用,但我无法找出正确的语法。有人可以帮我吗?

4

3 回答 3

5

假设您已经在别处定义了 $FilePath、$user 和/或 $computer,请尝试这样的操作。

$files = Get-ChildItem $FilePath\*.txt
foreach ($file in $files)
{
  (Get-Content $file) | 
  Foreach-Object { $content = $_ -replace "User:", "User: $user" ; $content -replace "Computer:", "Computer: $computer" } | 
  Set-Content $file
}

您可以使用;在 中分隔其他命令Foreach-Object,例如,如果您想为您的用户名和计算机名设置单独的命令。如果您没有将 Get-Content cmdlet 括在括号中,则会收到错误消息,因为当 Set-Content 尝试使用它时,该进程仍会打开 $file。

另请注意,使用 Powershell,双引号中的字符串将评估变量,因此您可以将 $user 放入字符串中以执行类似的操作"User: $user"

于 2013-08-13T15:51:08.457 回答
0

如果UserComputer位于不同的行,则需要一次阅读两行。的ReadCount参数Get-Content允许您这样做。

Get-ChildItem $FilePath -Include *.txt `
| Get-Content -ReadCount 2 `
| %{ $user = $_[0] -replace '^User: ', ''; $computer = $_[1] -replace '^Computer: ', ''; "$user $computer" } `
| Out-File outputfile.txt

这假设每个文件只包含精确形式的行

User: someuser
Computer: somecomputer
User: someotheruser
Computer: someothercomputer
...

如果不是这种情况,您将需要提供确切的文件格式。

于 2013-08-14T14:58:10.000 回答
0

尝试这个:

gci $FilePath -Include *.txt | % {
  gc $_.FullName | ? { $_ -match '^(?:User|Computer): (.*)' } | % { $matches[1] }
} | Out-File 'C:\path\to\output.txt'
于 2013-08-14T10:46:19.503 回答