5
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!

1 Answer 1

12

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.

Sign up to request clarification or add additional context in comments.

1 Comment

You were correct I was creating file a System.IO.FileInfo object. I was generating $file with get-childitem for a folder path. It doesnt need to stay as a System.IO.FileInfo object for what I need so I just converted it to a string $file.tostring() and I am able to use indexOf. Thanks for the help!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.