当前位置:网站首页 > 更多 > 玩电脑 > 正文

[玩转系统] 在 PowerShell 中检查变量是否包含字符串

作者:精品下载站 日期:2024-12-14 22:05:43 浏览:13 分类:玩电脑

在 PowerShell 中检查变量是否包含字符串


使用-like-match运算符以及Contains方法,您可以在PowerShell中检查变量是否包含字符串。

在使用脚本时检查变量是否包含特定字符串或模式是必不可少的,并且经常需要,这对于创建条件语句至关重要。

在本文中,我们将讨论如何使用 Like、Match 运算符和 Contains() 方法来检查变量是否包含特定子字符串。

如果变量包含字符串,则使用 -like 运算符

PowerShell 变量中带有通配符的 -like 运算符可用于比较字符串并查找变量是否包含字符串。

$greetings = "Hello! Welcome to ShellGeek website." 
if($greetings -like "*Shell*" ) 
{ 
   Write-Host "The variable contains the word 'ShellGeek'."
} 

在上面的 PowerShell 脚本中,变量 $greetings 存储字符串数据类型的值。

为了检查变量是否包含特定子字符串,我们使用了 if 语句,该语句使用带有通配符 * 的类似 运算符。如果条件评估为真,它将打印 if 语句中的消息。

上述脚本的输出找到变量中的子字符串并将其打印在控制台上。

The variable contains the word 'ShellGeek'.

如果变量包含字符串,则使用 -match 运算符

PowerShell 中的 -match 运算符允许您使用正则表达式来查找匹配模式。

$greetings = "Hello! Welcome to ShellGeek website."   

if($greetings -match "Shel[la]Gee[ke]" ) 
{
   Write-Host "The variable contains a variations of the word 'ShellGeek'."
}         

上面的 PowerShell 脚本使用 -match 运算符和正则表达式来比较字符串并查找模式匹配。

上述脚本的输出是:

The variable contains a variations of the word 'ShellGeek'.

使用 Contains 方法检查变量是否包含子字符串

使用Contains()方法检查变量是否包含指定的字符串。

$greetings = "Hello! Welcome to ShellGeek website."

if( $greetings.Contains("ShellGeek"))
{
  Write-Host "The variable contains the word 'ShellGeek'."
}

在上面的 PowerShell 脚本中,Contains 方法采用字符串作为输入参数来检查变量。

上述脚本的输出是:

The variable contains the word 'ShellGeek'.

结论

我希望上面关于如何使用 -like、-match 运算符和 Contains 方法检查变量是否包含字符串的文章对您有所帮助。

您可以在 ShellGeek 主页上找到有关 PowerShell Active Directory 命令和 PowerShell 基础知识的更多主题。

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯