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

有没有更好的方法来编写这个 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\

答案1

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

$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
}

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

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

答案2

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

输入文件:

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
}

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

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

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

相关内容