Why can't I lookup an array index inside a foreach loop in Powershell? -


first question on here forgive me if make mistakes, try stick guidelines.

i trying write powershell script populates 2 arrays data read in via csv file. i'm using arrays cross-reference directory names in order rename each directory. 1 array contains current name of directory , other array contains new name.

this seems working far. create , populate arrays, , using short input , index lookup check work can search 1 array current name , retrieve correct new name second array. when try implement code in foreach loop runs through every directory name, can't lookup array index (it keeps coming -1).

i used code in first answer found here template. read csv file powershell , capture corresponding data . here's modification input lookup, works fine:

$input = read-host -prompt "merchant"  if($merchant -contains $input) {     write-host "it's there!"     $find = [array]::indexof($merchant, $input)     write-host index $find } 

here foreach loop attempts use index lookup, returns -1 every time. know it's finding file because enters if statement , prints "it's there!"

foreach($file in get-childitem $targetdirectory) {     if($merchant -contains $file)     {         write-host "it's there!"         $find = [array]::indexof($merchant, $file)         write-host index $find     } } 

i can't figure out. i'm powershell newb maybe it's simple syntax problem, seems should work , can't find i'm going wrong.

your problem seems $merchant collection of file names (of type string), whereas $file fileinfo object.

the -contains operator expects $file string, since $merchant string array, , works expect (since fileinfo.tostring() returns file name).

indexof() isn't forgiving. recognizes none of items in $merchant of type fileinfo, never finds $file.

you can either refer directly file name:

[array]::indexof($merchant,$file.name) 

or, @petseral showed, convert $file string instead:

[array]::indexof($merchant,[string]$file) # or  [array]::indexof($merchant,"$file") # or  [array]::indexof($merchant,$file.tostring()) 

finally, can call indexof() directly on array, no need use static method:

$merchant.indexof($file.name) 

Comments

Popular posts from this blog

yii2 - Yii 2 Running a Cron in the basic template -

asp.net - 'System.Web.HttpContext' does not contain a definition for 'GetOwinContext' Mystery -

mercurial graft feature, can it copy? -