I would like to create a powershell function that can take 2 different types of inputs for one parameter.
The example I will use is a copy-file function.
If I call the function like this Copy-File –FileToCopy “c:\test” –FileDestination “c:\dest”
I would like the function to get all the files in the folder and copy them to the destination.
If I call the function like this Copy-File –FileToCopy “c:\filesToCopy.txt” –FileDestination “c:\dest”
I would like the function to get the list of files from the text file and then copy them to the filedestination.
So the part I am not sure how to figure out is how to get the –FileToCopy parameter to be intelligent and know what type of input I am giving it.
The actual code to copy the files I can do.
There may be more elegant methods, but you could do something like this:
1. Append “*” to your parameter value and use Test-Path against it. In this case, you’re treating it like a folder, therefore c:\test would become c:\test\*.
2a. If Test-Path returns true, you have a folder and can proceed with copying its content.
2b. If Test-Path returns false, go to step 3.
3. Use Test-Path against the parameter as it is. If it returns true, then it is a file.
Update
Actually, it’s much simpler than I thought. You can use parameter PathType with TestPath and specify if you’re looking for a folder or a file.
–
PathType Containerwill look for a folder.–
PahType Leafwill look for a file.