Powershell-如何根据字符分割字符串?

时间:2020-06-02 14:28:16

标签: powershell

我有一个需要解析并最终发送到sql表的pdf文件名列表,每个文件的解析部分都在自己的列中。我将如何根据破折号“-”拆分并最终将其放入表格中。

您将从什么cmdlet开始拆分一个角色?我需要根据破折号'-'进行拆分。

感谢您的帮助。

示例文件名:

  • tester-2458-full_contact_snapshot-20200115_1188.pdf
  • tester-2458-limited_contact_snapshot-20200119_9330.pdf

所需结果:

enter image description here

3 个答案:

答案 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]的所需属性中
  • 将PSCO发送到$Results集合
  • 在屏幕上显示
  • 将其发送到CSV以便以后使用

代码...

#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"