【问题标题】:Check if string is like regex检查字符串是否像正则表达式
【发布时间】:2016-09-29 20:25:04
【问题描述】:

我有一个包含许多用于在笔记本电脑或工作站上部署的应用程序的文件夹。现在这个文件夹变得一团糟,因为多人使用这个文件夹,每个人都使用不同的存储方法。因此,我想编写一个脚本,以一种我们总能找到它们的方式来帮助管理这些文件。

我想在 Powershell 中。

  1. 列出所有文件(.msi、.exe 甚至更多)
  2. 确定文件是否已正确存储(Developer\Application\Application_version_architecture.extension 即 Adob​​e\Flashplayer\Flashplayer_22_x64.msi)
  3. 如果为真,请留下。
  4. 如果不是,我质疑脚本的用户 关于应用程序的一些事情,所以脚本然后重命名和 将其移至正确的文件夹。

目前我被困在第 2 步。我想使用一个正则表达式来确定标准应该是什么。但是,它一直排除正确命名的应用程序。

我使用以下命令来检索文件名:

Get-ChildItem -Path $path -Recurse -Name

这将检索应用程序文件夹中具有完整路径的文件,例如 “Adobe\Flashplayer\Flashplayer_22_x64.msi” 或者当不正确时 “Adobe\flashplayeractivex.msi”

然后我使用以下正则表达式来检查它们是否正确

\w*\\\w*\\[a-zA-Z]*\_[0-9a-zA-Z\.]*\_(([x][6][4])|([x][8][6])|([b|B][o][t][h]))\.(([m|M][s|S][i|I])|([e|E][x|X][e|E]))

我已经确认正在处理Rubular。 但是,我无法让它与 powershell 一起使用。我尝试了以下方法:

if ($file -match '\w*\\\w*\\[a-zA-Z]*\_[0-9a-zA-Z\.]*\_(([x][6][4])|([x][8][6])|([b|B][o][t][h]))\.(([m|M][s|S][i|I])|([e|E][x|X][e|E]))') {......commands...}

由于转义,这似乎不起作用(Powershell 向我抛出了一些错误)。然后我尝试了:

$pattern = [regex]::Escape('\w*\\\w*\\[a-zA-Z]*\_[0-9a-zA-Z\.]*\_(([x][6][4])|([x][8][6])|([b|B][o][t][h]))\.(([m|M][s|S][i|I])|([e|E][x|X][e|E]))')
if ($file -match $pattern) {......commands...}

这没有给我错误,但没有工作,因为它没有“匹配”“Apple\iTunes\iTunes_12.3_x64.exe”,它在 Rubular 上匹配。

有没有人认识到这个问题或看到我做错了什么?

【问题讨论】:

    标签: regex powershell


    【解决方案1】:

    我不会在一个正则表达式中尝试所有这些。相反,我会单独检查每项政策:

    $path = 'C:\tmp'
    $validExtensions = @('.msi', '.exe')
    $filnameRegex = '\w+_[0-9a-zA-Z\.]+_(?:x32|x64|[b|B]oth)'
    
    Get-ChildItem -Path $path -Recurse | ForEach-Object {
        if (-not ($_.Extension -cin $validExtensions))
        {
            Write-Host "$($_.FullName) has an invalid extension."
        }
        if (-not ($_.BaseName -match $filnameRegex))
        {
            Write-Host "$($_.FullName) doesn't match the filename policy."
        }
    
       if (3 -ne ($_.FullName.Split([System.IO.Path]::DirectorySeparatorChar).Length `
        - $path.Split([System.IO.Path]::DirectorySeparatorChar).Length))
        {
            Write-Host "$($_.FullName) doesn't match the directory policy."
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2012-08-05
      • 1970-01-01
      • 1970-01-01
      • 2011-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-24
      • 2013-01-01
      相关资源
      最近更新 更多