在文本文件中查找特定字符串 - Powershell [英] Find specific String in Textfile - Powershell

查看:206
本文介绍了在文本文件中查找特定字符串 - Powershell的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这个问题可能是一个新人问题",但我可能犯了一个逻辑错误.

I know this question might be a "new guy question" but I probably made a logical mistake.

我有一个文本文件,我想搜索它是否包含字符串.我按如下所示尝试过,但它不起作用:

I have a text file and I want to search if it contains a string or not. I tried it as shown below but it doesn't work:

$SEL = "Select-String -Path C:\Temp\File.txt -Pattern Test"
if ($SEL -eq $null)
{
    echo Contains String
}
else
{
    echo Not Contains String
}

推荐答案

我认为这就是你想要做的:

i think this is what you are trying to do:

$SEL = Select-String -Path C:\Temp\File.txt -Pattern "Test"

if ($SEL -ne $null)
{
    echo Contains String
}
else
{
    echo Not Contains String
}

在您的示例中,您正在定义一个名为 $SEL 的字符串,然后检查它是否等于 $null(当然,它总是会评估为 false,因为你定义的字符串不是$null!)

In your example, you are defining a string called $SEL and then checking if it is equal to $null (which will of course always evaluate to false, because the string you define is not $null!)

此外,如果文件包含模式,它将返回如下内容:

Also, if the file contains the pattern, it will return something like:

C:\Temp\File.txt:1:Test

因此,请确保将您的 -eq 切换为 -ne 或交换您的 if/else 命令,因为当前您正在回显 Contains String$SEL$null 时,它是向后的.

So make sure to switch your -eq to -ne or swap your if/else commands around, because currently you are echoing Contains String when the $SEL is $null, which is backwards.

查看 SS64 以了解 PowerShell 中所有内容的说明和有用示例code> 和 cmd

Check SS64 for explanations and useful examples for everything in PowerShell and cmd

检查文件中是否存在字符串的另一种方法是:

Another way of checking if a string exists in the file would be:

If (Get-Content C:\Temp\File.txt | %{$_ -match "test"}) 
{
    echo Contains String
}
else
{
    echo Not Contains String
}

但这并没有给你一个关于文本存在于文件中的位置的指示.此方法的工作方式也有所不同,因为您首先使用 Get-Content 获取文件的内容,因此如果您需要在检查字符串是否存在后对这些包含执行其他操作,这可能很有用.

but this doesn't give you an indicaion of where in the file the text exists. This method also works differently in that you are first getting the contents of the file with Get-Content, so this may be useful if you need to perform other operations on those contains after checking for your string's existence.

这篇关于在文本文件中查找特定字符串 - Powershell的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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