powershell - if ... contains

Hofmann, Wolfgang 21 Reputation points
2022-02-16T15:54:31.953+00:00

the below script fails. Although some valuef in $plw are contained in $AS_PLW the if statement always returns false.

Can anybody help?

thank

best regards
Wolfgang

$AS_Shares = Get-SmbShare -CimSession $server | select name

$AS_PLW = Get-ChildItem -Path \$server\PLW$ | select name

ForEach ($PLW in $AS_PLW)
{
if ($AS_Shares -icontains $PLW)
{
write-host $PLW is shared
else
{
write-host $PLW not shared
}
}

Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,416 questions
0 comments No comments
{count} votes

Accepted answer
  1. Rich Matheisen 45,186 Reputation points
    2022-02-16T16:12:55.923+00:00

    When you post code, please use the "Code Sample" editor (it's the 5th icon from the left on the Format Bar and has the graphic "101 010"). Using the default (plain text) editor will mangle your code is strange ways. It also makes it difficult to separate explanatory text from the code.

    First, the placement of the "{" and "}" characters was wrong.
    Second, when you use the Select-Object cmdlet the result is a PSCustomObject and not the simple string value you expected. In your code, you'd have to use $PLW.name to get at that string. It also means that the test to see if $AS_Shares contains $PLW will always fail because your code was comparing an array of PSCustomObjects to see if another PSCustomObject was in the array.

    I think this is what you intended:

    $AS_Shares = Get-SmbShare -CimSession $server | Select-Object -Expand name
    $AS_PLW = Get-ChildItem -Path \\$server\PLW$ | Select-Object -Expand name
    
    ForEach ($PLW in $AS_PLW) {
        if ($AS_Shares -icontains $PLW) {
            Write-Host $PLW is shared
        }
        else {
            Write-Host $PLW not shared
        }
    }
    

    I think you'd benefit greatly by downloading this free PDF: Windows-PowerShell-4
    Read the 1st half and do the exercises before moving on to the 2nd half.


1 additional answer

Sort by: Most helpful
  1. Michael Taylor 49,251 Reputation points
    2022-02-16T16:13:53.697+00:00

    icontains does an exact match. Hence the only way it would return true is if $PLW exactly matches a value in $AS_Shares which I suspect it doesn't. It would be useful to see a sample of the array and value it is not finding. Most likely you probably should use like or match instead.

       if (($AS_Shares -ilike "*$PLW*").Length -gt 0)  
    
    0 comments No comments