Управление данными \ дедупликация в PowerShell
Привет, я хочу дедуплицировать некоторые данные и объединить столбцы из CSV. Не могу понять, как это сделать. Вот образец данных, с которыми я работаю:
cmmc,stig,descr
AC.1.001,SV-205663r569188_rule,The ability to set access permissions and auditing is critical to maintaining the security and proper access controls of a system. To support this volumes must be formatted using a file system that supports NTFS attributes.
AC.1.001,SV-205667r569188_rule,Inappropriate granting of user rights can provide system administrative and other high-level capabilities.
AC.1.002,SV-205663r569188_rule,The ability to set access permissions and auditing is critical to maintaining the security and proper access controls of a system. To support this volumes must be formatted using a file system that supports NTFS attributes.
AC.1.002,SV-205665r569188_rule,Enterprise Domain Controllers groups on domain controllers.
Я довольно близок к данным, которые ищу, но изо всех сил пытаюсь добавить
|<value of 'descr'>
после пункта во втором столбце:
Вот мой сценарий:
Import-CSV '.\input.csv' | Group-Object 'cmmc' |
ForEach-Object {
[PsCustomObject]@{
cmmc = $_.name
stig = $_.group.stig -Join '
'
}
} | Export-Csv '.\output.csv' -NoTypeInformation
Результат выглядит следующим образом (отформатирован для удобства чтения, имена столбцов опущены):
AC1.001 SV-205663r569188_rule
SV-205665r569188_rule
AC1.002 SV-205663r569188_rule
SV-205665r569188_rule
Но я ищу вот это:
AC.1.001 SV-205663r569188_rule|The ability to set access permissions and auditing is critical to maintaining the security and proper access controls of a system. To support this volumes must be formatted using a file system that supports NTFS attributes.
SV-205667r569188_rule|Inappropriate granting of user rights can provide system administrative and other high-level capabilities.
AC.1.002 SV-205663r569188_rule|The ability to set access permissions and auditing is critical to maintaining the security and proper access controls of a system. To support this volumes must be formatted using a file system that supports NTFS attributes.
SV-205665r569188_rule|Enterprise Domain Controllers groups on domain controllers.
1 ответ
Используйте следующее, в котором вычисляемые свойства используются в сочетании с <tcode id="4334204"></tcode> командлет, примененный к результатам вашего <tcode id="4334205"></tcode> вызов:
Import-Csv .\input.csv |
Group-Object cmmc |
Select-Object @{ Name = 'cmmc'; e = 'Name' },
@{ Name = 'stig_descr'; e = {
[array] $stigs, [array] $descrs, $i = $_.Group.stig, $_.Group.descr, 0
$sigs.ForEach( { $stigs[$i], $descrs[$i++] -join '|' }) -join "`n"
}
} | Export-Csv -NoTypeInformation -Encoding utf8 .\output.csv
Примечание:
• Ограничения типа для
$stigs
и
$descrs
необходимы для обработки случая, когда группа состоит только из одной записи, и в этом случае
$_.Group.sig
и
$_.Group.descr
из-за поведения перечисления элементов возвращать только одну строковую оценку, чем одноэлементный массив ; без
[array]
приведение, индексация (например,
[$i]
) затем будет выполняться на
[string]
экземпляры, которые вернут единственный символ в этой позиции из строки.
• В
Export-Csv
позвони, отрегулируй
-Encoding
по мере необходимости. UTF-8 без спецификации теперь используется по умолчанию в PowerShell (Core) 7+, и
-NoTypeInformation
там больше не требуется.
Полученный файл имеет следующее содержимое, показывающее использование внутренних символов новой строки столбца (которые защищены значением в целом, заключенным в
"..."
):
"cmmc","stig_descr"
"AC.1.001","SV-205663r569188_rule|The ability to set access permissions and auditing is critical to maintaining the security and proper access controls of a system. To support this volumes must be formatted using a file system that supports NTFS attributes.
SV-205667r569188_rule|Inappropriate granting of user rights can provide system administrative and other high-level capabilities."
"AC.1.002","SV-205663r569188_rule|The ability to set access permissions and auditing is critical to maintaining the security and proper access controls of a system. To support this volumes must be formatted using a file system that supports NTFS attributes.
SV-205665r569188_rule|Enterprise Domain Controllers groups on domain controllers."
Чтобы визуализировать, что это дает желаемые данные, вы можете повторно импортировать полученный файл и передать его по конвейеру. <tcode id="4334220"></tcode> с переключателем:
PS> Import-Csv .\output.csv | Format-Table -Wrap
cmmc stig_descr
---- ---------
AC.1.001 SV-205663r569188_rule|The ability to set access permissions and auditing is critical to maintaining the security and proper access controls of a system. To support this volumes must be formatted using a file system that supports NTFS attributes.
SV-205667r569188_rule|Inappropriate granting of user rights can provide system administrative and other high-level capabilities.
AC.1.002 SV-205663r569188_rule|The ability to set access permissions and auditing is critical to maintaining the security and proper access controls of a system. To support this volumes must be formatted using a file system that supports NTFS attributes.
SV-205665r569188_rule|Enterprise Domain Controllers groups on domain controllers.
Обратите внимание, что
-Wrap
учитывает символы новой строки внутри свойства, но дополнительно разбивает отдельные строки на несколько, если они слишком широки для окна консоли.