我对最佳做法有点暗淡。我正在创建一个删除早于文件的函数,但是我想添加一个名为-Remote
的交换机是可选的,但是当您选择使用它时,交换机需要强制性信息,如{{1}使用$Server
。
这样的事情:
Invoke-Command
脚本/功能
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"
(日志文件)作为可选项。谢谢您的帮助。我还是PowerShell的新手并试图弄清楚这些东西。
答案 0 :(得分:6)
您可以使用此类参数
Param (
[switch] $Remote = $false,
[string] $server = $(
if ($Remote)
{
Read-Host -Prompt "Enter remote server:"
}
)
)
在这种情况下,如果你在没有-Remote的情况下调用脚本,$ server将保持$ null。
如果您致电script.ps1 -Remote
,它会要求您输入服务器名称。
如果您像scripts.ps1 -Remote -server "Servername"
一样使用它,$ server将成为Servername。
基于switch将函数包装到Invoke-Command中可能很复杂,但是你总是可以使用Invoke-Command(它应该和direct命令一样快),只需使用这样的参数
Param (
[switch] $Remote = $false,
[string] $server = $(
if ($Remote)
{
Read-Host -Prompt "Enter remote server:"
}
else
{
"localhost"
}
)
)