Home > Mobile >  Powershell command shown different behavior in console and script execution
Powershell command shown different behavior in console and script execution

Time:01-14

I am doing a powershell script where it will trigger a product specific command and manipulate the returned result. The example of the returned result will look like the following

XXXX command completed  Thu Jan 13 16:59:59 2022 :XXXX, Account 'XXXX' on 'XXXX' modified successfully

So if the result contain modified successfully, it will do task A or vice versa based on the result. But I cant get the expected output when I run it inside my powershell script. Please refer to my script below

write-host "The type of variable :"$eTSuspend.GetType().Name
write-host "The string : "$eTSuspend.Contains('successfully')


FYI, $eTSuspend is the variable store the returned result by the command and here are my output from my script

The type of variable : Object[]
The string :  False 

I tried to check the data type of the variable but it shown `Object[]` and the string validation shown false. So I am bit confused because the result is different from what I executed all the powershell command directly in the powershell console. Here are the step I did in my powershell console
1) Copied the returned result and assigned to `$eTSuspend` manually
2) Executed $eTSuspend.GetType().Name - Yes,its a string data type
3) $eTSuspend.Contains('successfully') - Yes, result returned true
PS C:\Users\XXX.XXX> $eTSuspend.GetType().Name
String
PS C:\Users\XXX.XXX> $eTSuspend.Contains("successfully")
True

I really cant figured out why both of the same command `GetType()` and `-Contains` returned a different result when I executed with script and powershell console

CodePudding user response:

You're testing for two different kinds of containment.

  • String.Contains() performs a substring search - if the substring argument is found at any offset in the string, it returns true:
    • "abc def".Contains("def") returns $true, because the susbtring "def" can be extracted from "abc def" at offset 4.
  • Array.Contains() and the -contains operator tests for collection containment - that is, "does this array/list/collection contain an exact copy of the argument among it's members":
    • @("abc", "def").Contains("def") returns true because at least one of the items in the array satisfies that constraint - "def" and "def" are equivalent
    • @("abc", "def").Contains("de") returns false because none of the items in the array is exactly equivalent to "de", in other words:
      • "abc" -eq "de" is not true
      • "def" -eq "de" is not true either
      • There are no more items in the array to be tested, so it returns $false
  •  Tags:  
  • Related