I have a function that works with the invoke-command function either without any arguments or with all arguments. What I would like to do is run the function via invoke-command with only 1 argument. Here is my code
function remove-oldfiles {
param ([String]$days = 28,
[string]$path = "c:\temp\archive")
if ( -not (test-path $path) ) {throw "path not found"}
$cmd = ((Get-ChildItem -Path $path -Recurse |
where {$_.lastwritetime -lt (get-date).adddays(-$days) -and -not $_.psicontainer}))
$cmd
write-Host("do you want to delete the files? ") -ForegroundColor Red
$ans = (read-host).ToUpper()
if ($ans -eq 'Y') {
write-host("deleting files...")
$cmd | remove-item -Force
}
}
Both of these commands work:
Invoke-Command -ComputerName remote_machine -ScriptBlock ${function:remove-oldfiles} -ArgumentList 90, "c:\temp\archive"
Invoke-Command -ComputerName remote_machine -ScriptBlock ${function:remove-oldfiles}
But if I try and run it with only 1 argument it doesn't work. Tried:
Invoke-Command -ComputerName remote_machine -ScriptBlock ${function:remove-oldfiles} -ArgumentList '-path "c:\temp\archive"'
Invoke-Command -ComputerName remote_machine -ScriptBlock ${function:remove-oldfiles} -ArgumentList "c:\temp\archive"
Is it possible to use Invoke-Command
with -ArgumentList
with just some arguments and not all?
Invoke-Command
is not the problem. Your function has 2 parameters, where, positionally the first one is the$days
parameter, in your second example which "doesn't work" you're passing a path to that parameter. – Estes-ArgumentList
: The parameters in the script block are passed by position from the array value supplied to ArgumentList. This is known as array splatting. – Estes