1

I'm struggling to pass my arguments to my custom made function.

This works fine:

Delete-OldFiles -Target $Target -OlderThanDays $OlderThanDays -LogName Auto_Clean.log

These don't work at all:

# (using -ScriptBlock ${Function:Delete-OldFiles} for all calls)

Invoke-Command -ArgumentList ( ".$Target", ".$OlderThanDays", ".$LogName Auto_Clean.log")

Invoke-Command -ArgumentList @("$Target", "$OlderThanDays", "Auto_Clean.log") 

Invoke-Command -ArgumentList @({-OlderThanDays "10", -Target "E:\Share\Dir1", -LogName "Auto_Clean.log"})

Invoke-Command -ArgumentList (,@('$Target','$OlderThanDays','Auto_Clean.log'))

Can you help me on how to pass the following parameters correctly:

Param(
    [Parameter(Mandatory=$False,Position=1)]
    [String]$Server,
    [Parameter(Mandatory=$True,Position=2)]
    [ValidateScript({Test-Path $_})]
    [String]$Target,
    [Parameter(Mandatory=$True,Position=3)]
    [Int]$OlderThanDays,
    [Parameter(Mandatory=$True,Position=4)]
    [String]$LogName,
    [switch]$CleanFolders
)

1 Answer 1

4

When you use Invoke-Command -ArgumentList arguments are passed to script block as positional parameters. Looking at you param() block: it was not designed with using positional parameters in mind... Having optional parameters first, and mandatory after means you always need to provide optional parameter, or use named parameters for all mandatory ones.

In other words: having optional parameter in the first position will stop you from running this code in this fashion with Invoke-Command.

To test your code locally you should try it this way:

Delete-OldFiles $Target $OlderThanDays "Auto_Clean.log"

I would expect it to prompt you for LogName parameter.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you BartekB, I finally see it now. I changed the order of my parameters to have the $Servermentioned last and now it works fine. Thanks again man! I was really looking hard on this one...

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.