简体   繁体   中英

Powershell function with smart parameter

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 Container will look for a folder.
- PahType Leaf will look for a file.

I'd determine if it's a text file or a folder and go from there. The function below should get you started and after the script has been run it can be executed like Copy-Thing -filename "sourcefile.txt" -Destination "C:\\place"

Function Copy-Thing([string]$fileName,[string]$destination){
    $thing = Get-Item $fileName
    if ($thing.Extension -eq ".txt"){
        Get-Content | %{
            Copy-Item -Path $_ -Destination $destination
        }
    }
    elseif ($thing.PSIsContainer){
        Get-ChildItem -Path $fileName | %{
            Copy-Item -Path $_.FullName -Destination $destination
        }
    }
    else{
        Write-Host "Please specifiy a valid filetype (.txt) or folder"
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM