具有智能参数的Powershell功能

时间:2012-08-07 18:52:34

标签: powershell powershell-v2.0

我想创建一个powershell函数,它可以为一个参数提供2种不同类型的输入。

我将使用的示例是一个复制文件函数。

如果我像这样调用这个函数Copy-File –FileToCopy “c:\test” –FileDestination “c:\dest”
我希望该函数能够获取文件夹中的所有文件并将它们复制到目的地。

如果我调用此函数Copy-File –FileToCopy “c:\filesToCopy.txt” –FileDestination “c:\dest”

我希望该函数从文本文件中获取文件列表,然后将它们复制到文件目录中。

所以我不知道如何弄清楚如何让-FileToCopy参数变得聪明并知道我给它的输入类型。 复制我可以做的文件的实际代码。

2 个答案:

答案 0 :(得分:1)

可能有更优雅的方法,但你可以做这样的事情:
 1.在参数值后附加“*”并对其使用Test-Path。在这种情况下,您将其视为文件夹,因此 c:\ test 将变为 c:\ test \ *。
 2A。如果Test-Path返回 true ,则您有一个文件夹,可以继续复制其内容  2B。如果Test-Path返回 false ,请转到步骤3  3.按原样对参数使用Test-Path。如果它返回 true ,那么它就是一个文件。

<强>更新
实际上,它比我想象的要简单得多。您可以将参数PathType与TestPath一起使用,并指定您是在查找文件夹还是文件 - PathType Container会查找文件夹 - PahType Leaf将查找文件。

答案 1 :(得分:0)

我会确定它是文本文件还是文件夹并从那里开始。下面的函数应该让您开始,在脚本运行后,它可以像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"
    }
}