有没有更好的方式来编写这个PowerShell脚本?

下面是我的Powershell脚本删除我的服务器上的某些备份文件,然后显示其内容。 有很多重复。 有没有更有效的方式来执行这个任务?

Remove-Item \\ietg\z$\Backups\daily\ETG*.bkf -Force -Confirm Remove-Item \\icnt\Z$\Backups\Daily\cnt*.bkf -Force -Confirm Remove-Item \\igre\Z$\Backups\Daily\gre*.bkf -Force -Confirm Remove-Item \\ihvd\Z$\Backups\Daily\hvd*.bkf -Force -Confirm Remove-Item \\iklr\Z$\Backups\Daily\klr*.bkf -Force -Confirm Get-ChildItem \\ietg\z$\Backups\daily\ Get-ChildItem \\icnt\Z$\Backups\Daily\ Get-ChildItem \\igre\Z$\Backups\Daily\ Get-ChildItem \\ivd\Z$\Backups\Daily\ Get-ChildItem \\iklr\Z$\Backups\Daily\ 

将数据保存在同一个文件中的另一种方法是从两个数组构build哈希。

 $servers={"ietg", "icnt", "igre", "ihvd", "iklr"} $filenames={"ETG", "cnt", "gre", "hvd", "klr"} $Targets = @{} if ($servers.Length -ne $filenames.Length) { Write-Error -Message "Array lengths do not match" ` -Category InvalidData ` -TargetObject $values } else { for ($i = 0; $i -lt $keys.Length; $i++) { $Targets[$keys[$i]] = $values[$i] } } # the rest is from @sysadmin1138's post... Foreach ($Targ in $Targets) { $Child=""\\"+$Targ.Server+"\Z$\Backups\daily\"+$Targ.filename $Server=$Child+"*.bkf" Remove-Item $Server -Force -Confirm Get-ChildItem $Child } 

或者,更好的是,如果文件名总是服务器名称的一部分,则可以从一个数组构build数据,如下所示:

 $servers={"ietg", "icnt", "igre", "ihvd", "iklr"} $Targets = @{} $servers | %{ $Targets.Add( $_, $_.Substring(1,3) ) } # continue same as above starting from "Foreach ($Targ..." 

一种方法是让脚本在另一个文件中读取值对。 这将简化脚本,并使维护更容易。

input文件:

 Server,filename ietg,ETG icnt,cnt igre,gre ihvd,hvd iklr,klr 

然后像这样(我的头顶,不要跑,这里有错误)

 $Targets=Import-CSV -File "Input.csv" Foreach ($Targ in $Targets) { $Child=""\\"+$Targ.Server+"\Z$\Backups\daily\"+$Targ.filename $Server=$Child+"*.bkf" Remove-Item $Server -Force -Confirm Get-ChildItem $Child } 

stringbulding几乎肯定可以轻松完成。 关键是CSV导入和循环。

如果你想在一个文件中完成所有工作,你可以手动构build$Targets

 $Targets[0]= @{"Server" = "ietg"; "filename" = "ETG"} $Targets[1]= @{"Server" = "icnt"; "filename" = "cnt"} $Targets[2]= @{"Server" = "igre"; "filename" = "gre"} ## and so on