George Murphy
George Murphy

Reputation: 1097

Validate 2 Powershell Parameters

I have a PowerShell function that moves files and folders from one directory to another. I want to be able to make sure neither value for $fromFolder or $toFolder is empty or null. Not sure how it would work with two parameters.

function Move-Folders {
    gci $fromFolder -Recurse | ForEach-Object { Move-Item $_.FullName $toFolder }
    ii $toFolder
}

Upvotes: 0

Views: 93

Answers (2)

Manu
Manu

Reputation: 1742

Declare the parameters with validation attributes : about_Functions_Advanced_Parameters

function Move-Folders {
    Param
    (
        [parameter(Mandatory=$true)]
        [ValidateNotNullOrEmpty()]
        [String]
        $fromFolder,

        [parameter(Mandatory=$true)]
        [ValidateNotNullOrEmpty()]
        [String]
        $toFolder
    )

    gci $fromFolder -Recurse | ForEach-Object { Move-Item $_.FullName $toFolder }
    ii $toFolder
}

Upvotes: 2

Ranadip Dutta
Ranadip Dutta

Reputation: 9133

This should do your work with mandatory parameters:

function Move-Folders {
Param(
   [Parameter(Mandatory=$true)]
   $fromFolder,
   [Parameter(Mandatory=$true)]
   $toFolder

) #end param

gci $fromFolder -Recurse | ForEach-Object { Move-Item $_.FullName $toFolder }

ii $toFolder
}

Upvotes: 0

Related Questions