为什么我不能从我的数组中调用 Contains 方法? [英] Why can't i call Contains method from my array?

查看:58
本文介绍了为什么我不能从我的数组中调用 Contains 方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Arrrg!我正在用powershell 编写一个简单的脚本,我觉得这是一个愚蠢的问题.我正在调用一个调用存储过程的 sql 命令,结果我把它放在一个数组中.结果如下所示:

Arrrg!I am running into what i feel is a dumb issue with a simple script i'm writing in powershell. I am invoking a sql command that is calling a stored proc, with the results i put it a array. The results look something like this:

Status                                       ProcessStartTime                            ProcessEndTime                             
------                                       ----------------                            --------------                             
Expired                                      May 22 2010  8:31PM                         May 22 2010  8:32PM

我想做的是 if($s.Contains("Expired")) ,报告失败.简单的...?:(我遇到的问题是它看起来像没有加载包含方法,因为我收到这样的错误:

What i'm trying to do is if($s.Contains("Expired")) , report failed. Simple...? :( Problem i'm running into is it looks like Contains method is not being loaded as i get an error like this:

方法调用失败,因为 [System.Object[]] 不包含名为Contains"的方法.在行:1 字符:12+ $s.Contains <<<<(已到期")+ CategoryInfo : InvalidOperation: (Contains:String) [], RuntimeException+ FullQualifiedErrorId : MethodNotFound

那么,我该怎么做才能阻止 powershell 将其展开为字符串?下面的实际 ps 脚本 -

So, what can i do to stop powershell from unrolling it to string? Actual ps script below -

$s = @(Invoke-Sqlcmd -Query "USE DB
       GO
       exec Monitor_TEST_ps 'EXPORT_RUN',NULL,20" `
       -ServerInstance testdb002\testdb_002
      )

if ($s.Contains("Expired"))   
{
    Write-Host "Expired found, FAIL."
}
else 
{
    Write-Host "Not found, OK." 
}

推荐答案

您看到该方法的原因是 Get-Members 是 powershell 试图提供帮助并展开集合.如果您有一个包含多种类型项目的数组,它会向您显示每种类型的成员(例如,如果您使用ls"(Get-ChildItem)并且您所在的目录中有 FileInfos 和 DirectoryInfos,并且您使用管道 ls | gm,它将显示 FileInfos 的成员以及 DirectoryInfos 的另一组成员):

The reason you see the method is Get-Members is powershell is trying to be helpful and unrolling the collection. If you have an array with multiple types of items, it shows you the members for each type (like if you ‘ls’ (Get-ChildItem) and there are FileInfos and DirectoryInfos in the directory you are in, and you pipe ls | gm, it will show you members of FileInfos and also another group of members of DirectoryInfos):

(7) C:\ -» ls


    Directory: C:\


Mode                LastWriteTime     Length Name
----                -------------     ------ ----
d----         5/28/2010   8:19 AM            .hg
d----         5/13/2010   3:37 PM            Build
…
-a---         4/22/2010  11:21 AM       2603 TODO.org


(8) C:\ -» ls | gm


   TypeName: System.IO.DirectoryInfo

Name                      MemberType     Definition
----                      ----------     ----------
Mode                      CodeProperty   System.String Mode{get=Mode;}
Create                    Method         System.Void Create(System.Security.AccessControl.Direct...
…

   TypeName: System.IO.FileInfo

Name                      MemberType     Definition
----                      ----------     ----------
Mode                      CodeProperty   System.String Mode{get=Mode;}
AppendText                Method         System.IO.StreamWriter AppendText()
…

为了确保我没有查看展开的成员,我通常会先尝试$s.GetType().Name",看看我在处理什么.在您的情况下,它显然是数组,因为您将其初始化为$s = @(Invo"(@ = 它是一个数组.)

What I usually do, to make sure I am not looking at unrolled members, is try "$s.GetType().Name" first to see what I am dealing with. In your case, it’s clearly and array, since you initialized it like "$s = @(Invo" (the @ = it’s an array.)

要查明数组是否包含项目,可以使用 -contains 运算符:

To find out if an array contains an item, you can use the -contains operator:

(9) C:\ -» @(1,2,3) -contains 1
True

我认为您有一个字符串数组,因此您可以使用字符串文字,例如:

I think you’ve got an array of strings, so you can use a string literal, like:

(10) C:\ -» @("Stuff","you've","got","might have","Expired") -contains "Expired"
True

但如果 expired 不是完全匹配(您正在寻找包含 expired 的元素,例如Connection Expired 1/1/2010"),您需要找到匹配项并检查计数,我认为:

But if the expired isn’t an exact match (you were looking for an element that contains expired, like "Connection Expired 1/1/2010") you need to find matches and check the count, I think:

(23) C:\ -» @("Stuff","you've","got","might have","Connection Expired 1/1/2010") -contains "Expired"
False
(24) C:\ -» @("Stuff","you've","got","might have","Connection Expired 1/1/2010") | ?{$_.Contains("Expired")}
Connection Expired 1/1/2010
(33) C:\ -» $xs = @("Stuff","you've","got","might have","Connection Expired 1/1/2010") | ?{$_.Contains("Expired")}
(34) C:\ -» $xs.GetType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     String                                   System.Object


(35) C:\ -» $xs
Connection Expired 1/1/2010

在这种情况下,只有一个匹配项,因此 powershell 将其展开为一个字符串.混蛋.但是,如果匹配项超过 1 个:

In this case, there is only one match, so powershell unrolled it to a string. Jerk. If there are more than 1 matches, however:

(36) C:\ -» $xs = @("Stuff","you've","got","might Expired  have","Connection Expired 1/1/2010") | ?{$_.Contains("Expired")}
(37) C:\ -» $xs.GetType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Object[]                                 System.Array


(38) C:\ -» $xs
might Expired  have
Connection Expired 1/1/2010

现在是一个数组.

幸运的是,字符串和数组都有长度属性:

Luckily, both string and array have a length property:

(39) C:\ -» $xs.Length
2
(40) C:\ -» "Bob".Length
3

因此您可以检查包含已过期"的结果的长度,以查看是否有任何已过期的:

So you can check the length of your results that contain "Expired" to see if there are any expired’s:

(41) C:\ -» $xs = @("Stuff","you've","got","might Expired  have","Connection Expired 1/1/2010") | ?{$_.Contains("Expired")} 
(42) C:\ -» if ($xs.Length -gt 0) { Write-Host "Whoas, stuff's expired, dog." }
Whoas, shit's expired, dog.

(也许有人有更好的方法来检查集合是否包含满足某些谓词的项目(如 LINQ 的 Any)?)

(maybe someone has a better way to check if a collection contains an item that satisifies some predicate (like LINQ's Any)?)

这篇关于为什么我不能从我的数组中调用 Contains 方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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