我有一个需要解析并最终发送到sql表的pdf文件名列表,每个文件的解析部分都在自己的列中。我将如何根据破折号“-”拆分并最终将其放入表格中。
您将从什么cmdlet开始拆分一个角色?我需要根据破折号'-'进行拆分。
感谢您的帮助。
示例文件名:
所需结果:
答案 0 :(得分:1)
使用$ variable.split('-')将返回长度等于拆分操作产生许多元素的长度的字符串数组。
答案 1 :(得分:1)
还有一个-split
运算符。
https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_split
基本示例:
如果文件名位于$FilePaths
数组中。
foreach($filepath in $FilePaths)
{
$parts = $filepath -split '-';
[pscustomobject]@{"User" = $parts[0]; "AppID" = $parts[1]; "FileType" = $parts[2]; "FilePath"=$filepath }
}
答案 2 :(得分:1)
另一种方法是使用正则表达式和命名捕获组。 [咧嘴]
它做什么...
#region/#endregion
块,然后使用(Get-ChildItem).Name
或另一种为您提供纯字符串的方法。 $Null =
抑制False/True
调用的-match
输出$Match
自动变量将捕获的值插入[PSCustomObject]
的所需属性中$Results
集合代码...
#region >>> fake reading in a list of file names
# in real life, use (Get-ChildItem).Name
$InStuff = @'
tester-2458-full_contact_snapshot-20200115_1188.pdf
tester-2458-limited_contact_snapshot-20200119_9330.pdf
'@ -split [System.Environment]::NewLine
#endregion >>> fake reading in a list of file names
$Results = foreach ($IS_Item in $InStuff)
{
$Null = $IS_Item -match '^(?<User>.+)-(?<AppId>.+)-(?<FileType>.+)-(?<Date>.+)\.pdf$'
[PSCustomObject]@{
User = $Matches.User
AppId = $Matches.AppId
FileType = $Matches.FileType
Date = $Matches.Date
FileName = $IS_Item
}
}
# display on screen
$Results
# send to CSV file
$Results |
Export-Csv -LiteralPath "$env:TEMP\JM1_-_FileReport.csv" -NoTypeInformation
输出到屏幕...
User : tester
AppId : 2458
FileType : full_contact_snapshot
Date : 20200115_1188
FileName : tester-2458-full_contact_snapshot-20200115_1188.pdf
User : tester
AppId : 2458
FileType : limited_contact_snapshot
Date : 20200119_9330
FileName : tester-2458-limited_contact_snapshot-20200119_9330.pdf
C:\Temp\JM1_-_FileReport.csv
文件的内容...
"User","AppId","FileType","Date","FileName"
"tester","2458","full_contact_snapshot","20200115_1188","tester-2458-full_contact_snapshot-20200115_1188.pdf"
"tester","2458","limited_contact_snapshot","20200119_9330","tester-2458-limited_contact_snapshot-20200119_9330.pdf"