PowerShell查看是否存在与env:systemroot匹配且具有较长名称正则表达式的文件夹

问题描述 投票:0回答:2

我测试是否有一个名为\ windows \ software的文件夹,我正在使用这个powershell代码,这是有效的。

$PathBackup = Test-Path Env:\systemroot\software -IsValid
If ($PathBackup -eq $true) {Write-host "There is backup's"}
Else {write-Verbose "There is no backup's of folder \software*"}

但我真正想要的是测试是否有任何其他文件夹与\ software *******文件夹匹配,而不是\ software \文件夹本身。

我怎么能用正则表达式做到这一点?

我试过这个,但没有运气:

$PathBackup = Test-Path Env:\systemroot\software -IsValid | Where { $_ -match '\w{8,}'}
regex powershell
2个回答
1
投票

可能最直接的方式是使用Get-ChildItem和通配符globbing。其中?匹配任何字符,*为任何字符的零或更多。

这将匹配\软件备份,但不匹配\软件或\备份软件

 if (Get-ChildItem "$Env:SystemRoot\software?*") {
     Write-Verbose "There are backups"
 } else {
     Write-Verbose "There are no backups of folder \software*"
 }

这将匹配\ software backup,\ software和\ backup软件

  if (Get-ChildItem "$Env:SystemRoot\*software*") {
      Write-Verbose "There are backups"
  } else {
      Write-Verbose "There are no backups of folder \software*"
  }

这将匹配\ softwarebackup和\ backupsoftware但不匹配\ software

  #Using Globbing

  if (@((Get-ChildItem "$Env:SystemRoot\software?*"),(Get-ChildItem "$Env:SystemRoot\?*software")) | Where-Object {$_}) {
      Write-Verbose "There are backups"
  } else {
      Write-Verbose "There are no backups of folder \software*"
  }

  #using regex

  if (Get-ChildItem "$Env:SystemRoot" | Where-Object {$_.Name -match '.+software$|^software.+'}) {
      Write-Verbose "There are backups"
  } else {
      Write-Verbose "There are no backups of folder \software*"
  }

0
投票

不知道这是不是最好的方法,但我想我得到了:

$PathBackup = Test-Path Env:\systemroot\software -IsValid | Where { $_ -match 'software+\w'}
© www.soinside.com 2019 - 2024. All rights reserved.