Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$string.IndexOf('.') inside powershell function returns method invocation failed

Function doSomething($param1 $param2 $file)
{
...doing stuff
$pos = $file.IndexOf('.')
}

doSomething -param1 'stuff' -param2 'more stuff' -file 'C:\test.txt'

Returns error: Method invocation failed because [System.IO.FileInfo] doesn't contain a method named 'IndexOf'.

But calling it outside a function or from the command line works with out issue.

Is this a limitation of powershell or is there some trick to calling string functions inside powershell functions?

Thanks for the help!

like image 667
Dane Boulton Avatar asked Dec 20 '22 23:12

Dane Boulton


1 Answers

IndexOf is a method of type string. I suspect that somewhere in ...doing stuff, you're operating on $file in such a way that it becomes treated as a System.IO.FileInfo.

I suspect this in part because I've tried to replicate it in my environment and got it to work:

function doSomething ($file) 
{ 
    # This gets the index of . in 'C:\test.txt', which should be at position 7.
    $pos = $file.IndexOf('.')
    $pos
    $file.GetType() 
}
doSomething -file 'C:\test.txt'
7

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

Are you operating on $file at all, or using it to modify other files? If you are and don't mind the object being a [System.IO.FileInfo], you can use $file.fullname to get your path string back. This assumes that you haven't modified it in such a way that it has become a collection of FileInfo objects.

like image 54
Anthony Neace Avatar answered Jan 14 '23 06:01

Anthony Neace