使用 PowerShell 匹配存储在变量中的字符串 [英] Match strings stored in variables using PowerShell

查看:49
本文介绍了使用 PowerShell 匹配存储在变量中的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个备份脚本来移动 30 天之前的文件,但我希望能够从列表中排除文件夹

I am attempting to create a backup script that will move files that are older that 30 days, but I want to be able to exclude folders from the list

$a = "C:\\Temp\\Exclude\\test"
$b = "C:\\Temp\\Exclude"

如果我运行以下:

$a -match $b

遵循 PowerShell 基础知识:条件运算符 -Match -Like -Contains &-In -NotIn:

$Guy ="Guy Thomas 1949"
$Guy -match "Th"

这将返回 true.

推荐答案

我想说使用通配符之类的操作符,它可以为您省去很多头痛:

I'd say use wilcards and the like operator, it can save you a lot of head aches:

$a -like "$b*"

匹配运算符使用正则表达式模式,并且路径中包含正则表达式特殊字符(转义字符).如果您仍想使用 -match - 请确保对字符串进行转义:

The match operator is using regex pattern and the path is having regex special characters in it (the escape characeter). If you still want to use -match - make sure to escape the string:

$a -match [regex]::escape($b)

这会起作用,但请记住,它可以在字符串的中间匹配,您可以添加^"锚点以告诉正则表达式引擎从字符串的开头进行匹配:

This will work but keep in mind that it can match in the middle of the string, you can add the '^' anchor to tell the regex engine to match from the begining of the string:

$a -match ("^"+[regex]::escape($b))

这篇关于使用 PowerShell 匹配存储在变量中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆