2014-05-21 2 views
2

나는 모범 사례가 될 것이라고 어둠 속에서 조금 있습니다. 이전 버전의 파일을 삭제하는 기능을 만들고 있지만 선택 사항 인 -Remote 스위치를 추가하고 싶습니다. 스위치를 사용하기로 결정하면 $Server과 같은 필수 정보에 다음과 같은 전체 기능을 실행해야합니다. Invoke-Command을 사용하여 원격 서버. 이 같은PowerShell 스위치 매개 변수에 입력이 필요합니다.

뭔가 :

Delete-OldFiles -Target "\\Share\Dir1" -OlderThanDays "10" -LogName "Auto_Clean.log" -Remote "SERVER1"

스크립트/기능

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 & 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" 

나는 이것이 내가하는 옵션의 부 $LogName (로그 파일)을 만들 수 있습니다 마스터합니다. 도와 줘서 고마워. 저는 PowerShell을 아직 처음 사용하고 있으며 이러한 문제를 해결하려고합니다.

+1

같은 매개 변수를 사용하여 호출-명령을 사용할 수 있습니다 파라미터 세트 살펴보기 http://blogs.msdn.com/b/powershell/archive/2008/12/23/powershell-v2-parametersets.aspx –

답변

5

당신은 당신이 - 원격없이 스크립트를 호출하는 경우, $ 서버는 $ null로 유지됩니다,이 경우이

Param (
[switch] $Remote = $false, 
[string] $server = $( 
    if ($Remote) 
     { 
      Read-Host -Prompt "Enter remote server:" 
     } 
    ) 
) 

같은 매개 변수를 사용할 수 있습니다.

script.ps1 -Remote으로 전화하면 서버 이름을 입력하라는 메시지가 표시됩니다.

scripts.ps1 -Remote -server "Servername"과 같이 사용하면 $ server는 Servername이됩니다.

이 스위치를 기반으로 호출-명령으로 기능을 래핑하는 복잡 할 수 있지만, 당신은 항상 (이 빠른 속도로 직접 명령으로해야한다)가, 그냥이

Param (
[switch] $Remote = $false, 
[string] $server = $( 
    if ($Remote) 
     { 
      Read-Host -Prompt "Enter remote server:" 
     } 
    else 
     { 
      "localhost" 
     } 
    ) 
) 
+0

와르 고맙습니다. 내 함수'Function Delete-OldFiles'를 넣어야합니까? 아니면'Function Delete-OldFiles'를 호출하는 별도의 함수로 사용합니까? – DarkLite1

+0

전체 스크립트 또는 함수에서이 매개 변수를 사용할 수 있습니다. 매개 변수는 지정할 위치에 따라 다릅니다. 내가 알기 론, 전체 스크립트를 -Remote 스위치로 호출해야하므로, 매개 변수로 시작해야하고, 함수 (여기에서 스크립트 매개 변수에 액세스 할 수 있습니다)를 호출해야합니다. 마지막으로 함수를 호출합니다. –

관련 문제