【问题标题】:Remove part of the string in powershell in hashtable删除哈希表中powershell中的部分字符串
【发布时间】:2018-11-22 17:21:00
【问题描述】:

我有司机名单

$HashTable = Get-WindowsDriver –Online -All | Where-Object {$_.Driver -like "oem*.inf"} | Select-Object Driver, OriginalFileName, ClassDescription, ProviderName, Date, Version
Write-Host "All installed third-party drivers" -ForegroundColor Yellow
$HashTable | Sort-Object ClassDescription | Format-Table

该表在 OriginalFileName 列中显示完整的 inf 文件路径。我需要切断完整路径,例如

C:\Windows\System32\DriverStore\FileRepository\pantherpointsystem.inf_amd64_bde4cf569a728803\pantherpointsystem.inf

pantherpointsystem.inf.

所有行都是这样。

【问题讨论】:

标签: powershell


【解决方案1】:

要从完整路径中拆分文件名,您可以使用 Powershells Split-Path cmdlet,如下所示:

$FullPath = "C:\Windows\System32\DriverStore\FileRepository\pantherpointsystem.inf_amd64_bde4cf569a728803\pantherpointsystem.inf"
$FileName = $FullPath | Split-Path -Leaf

或像这样使用 .NET:

$FullPath = "C:\Windows\System32\DriverStore\FileRepository\pantherpointsystem.inf_amd64_bde4cf569a728803\pantherpointsystem.inf"
$FileName = [System.IO.Path]::GetFileName($FullPath)

在您的情况下,我会使用计算属性来填充 Hashtable:

$HashTable = Get-WindowsDriver –Online -All | 
                Where-Object {$_.Driver -like "oem*.inf"} | 
                Select-Object Driver, @{Name = 'FileName'; Expression = {$_.OriginalFileName | Split-Path -Leaf}},
                              ClassDescription, ProviderName, Date, Version

Write-Host "All installed third-party drivers" -ForegroundColor Yellow
$HashTable | Sort-Object ClassDescription | Format-Table

【讨论】:

    【解决方案2】:

    试试这个 -

    $FullPath = "C:\Windows\System32\DriverStore\FileRepository\pantherpointsystem.inf_amd64_bde4cf569a728803\pantherpointsystem.inf"
    $Required = $FullPath.Split("\")[-1]
    

    【讨论】:

      【解决方案3】:

      另一种解决方案是RegEx 一个:

      $FullPath = "C:\Windows\System32\DriverStore\FileRepository\pantherpointsystem.inf_amd64_bde4cf569a728803\pantherpointsystem.inf"
      $FullPath -match '.*\\(.*)$'
      $Required = $matches[1]
      

      .*\\(.*)$ 匹配最后一个破折号之后\ 和行尾$ 之前的所有字符

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-08-29
        • 2021-12-30
        • 2014-03-28
        • 1970-01-01
        • 2011-11-19
        • 1970-01-01
        相关资源
        最近更新 更多