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

Function doSomething($param1 $param2 $file) { ...doing stuff $pos = $file.IndexOf('.') } doSomething -param1 'stuff' -param2 'more stuff' -file 'C:\test.txt' 

Error while returning: the method call failed because [System.IO.FileInfo] does not contain a method named "IndexOf".

But calling it outside of a function or from the command line works without problems.

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

Thanks for the help!

+4
source share
1 answer

IndexOf is a method of type string . I suspect that somewhere in ...doing stuff you are working on $file in such a way that it is considered as System.IO.FileInfo .

I suspect this in part because I am trying to reproduce it in my environment and make it 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 

Do you generally work with $file or use it to modify other files? If you don't mind the object being [System.IO.FileInfo] , you can use $file.fullname to return the path string. This assumes that you have not changed it so that it becomes a collection of FileInfo objects.

+11
source

All Articles