0

我目前正在编写一个 PowerShell 脚本,该脚本可以读取多个工作站上的默认打印机,并将文本文件中的信息写入网络驱动器。我关于脚本中一些文本替换的最后一个问题已成功解决。但现在我在做第二部分。

Get-WmiObject -Class Win32_Printer -Filter "Default = $true" | % {
  $_.Name -replace '(?:.*)\\NDPS-([^\.]+)(?:.*)', 'PS-$1'
} | Out-File -FilePath "H:\daten\printer\$($env:COMPUTERNAME)_defaultprinter.txt"
Get-WmiObject Win32_Printer -Filter "Default = $true" `
  | Select-Object -expandProperty Name `
  | Out-File -FilePath "P:\batch\migration\Printer\$($env:COMPUTERNAME)_$($env:USERNAME)_defaultprinter.txt"

所提供代码的最后一行将默认打印机写入网络驱动器。现在我有近 1500 个单个 txt 文件。为了更好地分析,我使用以下 PowerShell 脚本将所有单个 txt 文件合并到一个大文件中。

Get-ChildItem -path \\samplepath\prgs\prgs\batch\migration\Printer -recurse | ? {
  ! $_.PSIsContainer
} | ? {
  ($_.name).contains(".txt")
} | % {
  Out-File -filepath \\samplepath\prgs\prgs\batch\migration\Printer\gesamt_printer.txt -inputobject (get-content $_.fullname) -Append
}

我收到一个文件,其中包含来自每个 txt 文件的默认打印机信息,但$($env:USERNAME)除了在线打印机信息之外,我还需要文件名中的 -part 作为单独的值才能使用 Excel 中的数据。有人可以告诉我如何在合并文件中插入文件名中的部分吗?

4

1 回答 1

0

您可以像这样从文件名中提取用户名部分:

$_.Name -match '^.*?_(.*)_.*?\.txt$'
$username = $matches[1]

正则表达式中的组(可通过 访问$matches[1])包含文件名中第一个和最后一个下划线之间的文本。

你可以像这样使用它:

$root    = "\\samplepath\prgs\prgs\batch\migration\Printer"
$outfile = "$root\gesamt_printer.txt"

Get-ChildItem $root -Recurse | ? {
  -not $_.PSIsContainer -and $_.Extension -eq ".txt"
} | % {
  $_.Name -match '^.*?_(.*)_.*?\.txt$'
  $username = $matches[1]
  $content  = Get-Content $_.FullName
  "{0},{1}" -f ($content, $username) | Out-File $outfile -Append
}

您也可以直接创建 CSV:

$root    = "\\samplepath\prgs\prgs\batch\migration\Printer"
$outfile = "$root\gesamt_printer.txt"

$getPrinter = { Get-Content $_.FullName }
$getUser    = { $_.Name -match '^.*?_(.*)_.*?\.txt$' | Out-Null; $matches[1] }

Get-ChildItem $root -Recurse `
  | ? { -not $_.PSIsContainer -and $_.Extension -eq ".txt" } `
  | select @{n="Username";e=$getUser},@{n="Printer";e=$getPrinter} `
  | Export-Csv $outfile -NoTypeInformation

请注意,这些代码示例不包含任何检查以排除其中没有至少两个下划线的文件名。

于 2013-03-12T11:33:48.290 回答