title: PowerShell Switch parameter requires input
body: <p>I'm a bit in the dark on what would be best practice. I'm creating a function to delete files older than, but I would like to add a switch called <code>-Remote</code> that is optional, but when you choose to use it, the switch requires mandatory information like <code>$Server</code> to have the whole function below executed on the remote server by using the <code>Invoke-Command</code>.</p>
  
  <p>Something like this:</p>
  
  <p><code>Delete-OldFiles -Target "\\Share\Dir1" -OlderThanDays "10" -LogName "Auto_Clean.log" -Remote "SERVER1"</code> </p>
  
  <p><strong>The script/function</strong></p>
  
  <pre><code>Function Delete-OldFiles
  {
  [CmdletBinding()]
  Param(
      [Parameter(Mandatory=$True,Position=1)]
      [ValidateScript({Test-Path $_})]
      [String]$Target,
      [Parameter(Mandatory=$True,Position=2)]
      [Int]$OlderThanDays,
      [Parameter(Mandatory=$True,Position=3)]
      [String]$LogName
        )
  
  if ($PSVersionTable.PSVersion.Major -ge "3") {
  
  # PowerShell 3+ Remove files older than (FASTER)
      Get-ChildItem -Path $Target -Exclude $LogName -Recurse -File | 
      Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-$OlderThanDays) } | ForEach {
          $Item = $_.FullName
          Remove-Item $Item -Recurse -Force -ErrorAction SilentlyContinue
          $Timestamp = (Get-Date).ToShortDateString()+" | "+(Get-Date).ToLongTimeString()      
          # If files can't be removed
          if (Test-Path $Item)
              { "$Timestamp | FAILLED: $Item (IN USE)" } 
          else
              { "$Timestamp | REMOVED: $Item" }  
          } | Tee-Object $Target\$LogName -Append } # Output file names to console &amp; logfile at the same time
  
  Else {               
  
  # PowerShell 2 Remove files older than
  Get-ChildItem -Path $Target -Exclude $LogName -Recurse | 
      Where-Object { !$_.PSIsContainer -and $_.LastWriteTime -lt (Get-Date).AddDays(-$OlderThanDays) } | ForEach {
          $Item = $_.FullName
          Remove-Item $Item -Recurse -Force -ErrorAction SilentlyContinue
          $Timestamp = (Get-Date).ToShortDateString()+" | "+(Get-Date).ToLongTimeString()      
          # If files can't be removed
          if (Test-Path $Item)
              { 
              Write-Host "$Timestamp | FAILLED: $Item (IN USE)"
              "$Timestamp | FAILLED: $Item (IN USE)"
               } 
          else
              { 
              Write-Host "$Timestamp | REMOVED: $Item"
              "$Timestamp | REMOVED: $Item"
              }  
          } |  Out-File $Target\$LogName -Append } 
  }
  
  Delete-OldFiles -Target "\\Share\Dir1" -OlderThanDays "10" -LogName "Auto_Clean.log" 
  #Delete-OldFiles "E:\Share\Dir1" "5" "Auto_Clean.log"
  </code></pre>
  
  <p>When I master this I can make the <code>$LogName</code> (logfile) optional to. Thank you for your help. I'm still new to PowerShell and trying to figure this stuff out.</p>