2

I'm having some difficulties passing the switch -CleanFolders to a function by using Invoke-Command. I found this, but I don't really know how to implement it as it's not targeted to a function.

Calling my function like this works fine:

Delete-OldFiles $Target $OlderThanDays $Server -CleanFolders
Invoke-Command -ComputerName $Server -Credential $Credentials -ScriptBlock ${Function:Delete-OldFiles} -ArgumentList ($Target, $OlderThanDays, $Server)

But this doesn't work at all:

Invoke-Command -ComputerName $Server -Credential $Credentials -ScriptBlock ${Function:Delete-OldFiles} -ArgumentList ($Target, $OlderThanDays, $Server, -CleanFolders)

1 Answer 1

2

Try like this:

$sb = {
  function Delete-OldFiles {
    #...
  }

  Delete-OldFiles $args[0] $args[1] $args[2] -CleanFolders:$args[3]
}

Invoke-Command -ComputerName $Server -Authentication Credssp `
  -Credential $Credentials -ScriptBlock $sb `
  -ArgumentList ($Target, $OlderThanDays, $Server, $true)
Sign up to request clarification or add additional context in comments.

7 Comments

This seems to be only working when I change this if ($CleanFolders) to this if ($CleanFolders=$True), but then it always works...
@DarkLite1 There is no conditional in the code you posted. Please update your question with the rest of your code. Also, = is an assignment operator in PowerShell, not a comparison operator. That would be -eq.
@DarkLite1 Evaluating the switch -CleanFolders in a statement if ($CleanFolders) worked just fine for me.
You're right, I've did a full update on the code because I didn't copy paste everything. Now you can see the full source.. The problem is that the function can't be executed by Invoke-Command because it's in the script block $JobFuncnow, it only works for Start-Joband I can't seem to find the correct syntax for Invoke-Command. Sorry for the confusion...
@DarkLite1 Can't you define a scriptblock containing the function as well as the function call and use that scriptblock for both Start-Job and Invoke-Command? See updated answer.
|

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.