有没有更好的方法来编写这个 powershell 脚本?

Jak*_*ake 2 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\
Run Code Online (Sandbox Code Playgroud)

sys*_*138 8

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

输入文件:

Server,filename
ietg,ETG
icnt,cnt
igre,gre
ihvd,hvd
iklr,klr
Run Code Online (Sandbox Code Playgroud)

然后是这样的(在我的头顶上,不要运行。这是错误)

$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
}
Run Code Online (Sandbox Code Playgroud)

几乎肯定可以更轻松地完成字符串构建。这里的关键是 CSV 导入和循环。

如果您更愿意在单个文件中完成所有操作,您可以$Targets非常简单地手动构建:

$Targets[0]= @{"Server" = "ietg"; "filename" = "ETG"}
$Targets[1]= @{"Server" = "icnt"; "filename" = "cnt"}
$Targets[2]= @{"Server" = "igre"; "filename" = "gre"}
## and so on
Run Code Online (Sandbox Code Playgroud)