问题描述
我创建了一个相当简单的循环,可以从活动目录中提取数据。这工作得很好,但我遇到的问题是所需的导出。根据供应商的说法,输出需要是一个不带引号的 txt 文件,作为一个 TXT 文件,以及 tab 作为分隔符,因为它将被导入到 sql 中。从 csv 中删除引号非常简单,但是我发现标题中带有逗号的用户在使用输出文件时会破坏一切。这是我的粗略脚本。
$Users = Get-Aduser -searchbase 'OU=Users,DC=Company,DC=com'
$Array = [System.Collections.ArrayList]@()
ForEach ($User in $Users){
$match = New-Object PSObject
$match | Add-Member NoteProperty "User Name" $User.sAMAccountName
$match | Add-Member NoteProperty "Password" "Password1"
$match | Add-Member NoteProperty "First Name" $User.givenname
$match | Add-Member NoteProperty "Last Name" $User.surname
$match | Add-Member NoteProperty "E-mail Address" $User.mail
$match | Add-Member NoteProperty "Business Title" $User.Title
$match | Add-Member NoteProperty "Department/Function" $User.Department
$match | Add-Member NoteProperty "Country" $User.c
$Array += $match
}
#Export LMS file removing comma as delimiter and making tab the delimiter
$Array | Export-csv -Delimiter "`t" -path c:\temp\Array.csv -Encoding UTF8 -NoType@R_95_4045@ion
#Import the csv file,convert to CSV removing all "" and export final file at tab delimited txt file
$Array2 = Import-csv C:\temp\Array.csv | ConvertTo-Csv -NoType@R_95_4045@ion | % { $_ -replace '"','' } | Select -Skip 1 | Out-File C:\temp\Import.txt
我将分隔符从逗号更改为制表符 "-Delimeter "`t" 并以 UTF8 编码导出,因为我们在其他国家/地区的用户使用了国际字符。 导出的 csv 看起来很好。当我将 csv 重新导入 powershell 并尝试删除引号时,会中断。当我将任何具有标题的用户(例如“Director,NA Infrastructure”)归档时,逗号后的所有内容都将被删除。我如何转换它并只删除引号但保留其他所有内容?
感谢您的支持。
编辑 1--
输出结果如下:
User Name Password First Name Last Name E-mail Address Business Title Department/Function Country
01234567 Password1 John Doe [email protected] Director,NA Infrastructure IT US
当使用 export-csv 或 out-fil 时,会删除之后的所有内容,所以它只是
01234567 Password1 John Doe [email protected] Director
编辑 2 --- 我稍微改变了一些东西并开始尝试使用 export-csv 直接到 txt。然后删除引号。这可能有效。与供应商核对
#Export file removing comma as delimiter and making tab the delimiter
$Array | Export-csv -Delimiter "`t" -path c:\temp\Array.txt -Encoding UTF8 -NoType@R_95_4045@ion
#Import the csv file,convert to CSV removing all "" and export final file at tab delimited txt file
$LArray2 = (Get-Content C:\Temp\Array.txt -Encoding UTF8) | ForEach-Object {$_ -replace '"',''} | Out-File C:\temp\Array_Final.txt
我试着考虑用记事本++打开,然后做工作并保存,但除了用记事本++打开文件并使用自动化之外,我看不出如何做。
解决方法
如果您在 PowerShell 7.0+ 中运行该脚本,您可以利用新引入的 Export-Csv
-UseQuotes Never
(More info here) 参数,并结合 -Delimiter "`t"
参数.这将为您提供不带引号的制表符分隔输出。
$Array | Export-csv -Delimiter "`t" -UseQuotes Never -Path c:\temp\Import.txt -Encoding UTF8 -NoTypeInformation