0

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
}
2
  • You create a function that does exactly the same as Move-Item. There's no need to browse with gci as you move everything without filtering so just use Move-Item, it will be more accurate. However I have provided an answer with how to validate your parameters. Commented Nov 10, 2017 at 14:10
  • 1
    Possible duplicate of Find if PowerShell argument is an empty string and prompt for input Commented Nov 10, 2017 at 14:41

2 Answers 2

2

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
}
Sign up to request clarification or add additional context in comments.

2 Comments

For reference: they're called attributes. Also, as a code style point, I'd recommend putting each attribute above the [Type]$Declaration on its own line for readability. In some scripts I've written, I've used [ValidateScript()] or have multiple attributes where your method quickly becomes unruly.
I agree with you, I did one-liner because of the ValidateNotNullOrEmpty() that is simple. I edit to follow the good practice rules.
0

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
}

Comments

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.