简体   繁体   中英

How to solve the “'IndexOf'.” error in PowerShell script

While running the below script I am getting an error:

"Method invocation failed because [System.Management.Automation.PSCustomObject] doesn't contain a method named 'IndexOf'".

Please help me to find out a solution to avoid the above error while running the below script.

Code:

$serverlist_csv1 = Import-Csv -Path $file1
$serverlist_temp1 = $serverlist_csv1
$exclude_serverlist_csv = Import-Csv -Path $file2
foreach ($server in $exclude_serverlist_csv) {
    $servers1 = ($serverlist_csv1.'SourceHostName' | Select-Object -ExcludeProperty 'SourceHostName')

    if ($servers1 -contains $server.'Exclude Server') {
        $server_object1 = ($serverlist_csv1 | Where-Object {$_.SourceHostName -eq $server.'Exclude Server'})

        $serverindex1 = $serverlist_csv1.IndexOf($server_object1) 
        $dataResizable1 = {$serverlist_csv1}.Invoke()
        $dataResizable1.RemoveAt($serverindex1)
        $serverlist_csv1 = $dataResizable1
    }
}

You are getting that error because you used select-object on the pipeline invocation of $serverlist_csv1, which creates a layer over the object effectively creating a new object a pscustomobject and that makes it lose the indexOf() method.

if you avoid this step and instead try for instance to exclude that on the import of the csv or modify the member to nothing if that property isn't necessary to you. The point is like people before me said that does not seem like the better way to solve whatever problem this is.

Build a list of the server names from the second file:

$exclude = Import-Csv $file2 | Select-Object -Expand 'Exclude Server'

Then filter the first file for rows whose SourceHostName column isn't one of those names and write the result back to a file:

Import-Csv $file1 | Where-Object {
    $exclude -notcontains $_.SourceHostName
} | Export-Csv 'C:\output.csv' -NoType

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM