Existe uma maneira melhor de escrever este script do powershell?

2

Abaixo está o meu script Powershell para excluir certos arquivos de backup em meus servidores e, em seguida, exibir seu conteúdo. Há muita repetição. Existe uma maneira mais eficiente de realizar essa tarefa?

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\
    
por Jake 13.07.2011 / 16:04

2 respostas

1

Outra maneira de manter os dados no mesmo arquivo é criar o hash de duas matrizes ...

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

Ou, melhor ainda, se os nomes de arquivos sempre fizerem parte do nome do servidor, você pode construir os dados de um array, assim:

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

Uma maneira é ter o script lido em outro arquivo para os pares de valores. Isso simplificará o script e tornará a manutenção muito mais fácil.

Arquivo de entrada:

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

Então algo assim (fora do topo da minha cabeça, não corra. Aqui estão erros)

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

O agrupamento de strings pode ser feito com facilidade. A principal coisa aqui é a importação de CSV e o loop.

Se você preferir fazer tudo em um único arquivo, pode construir $Targets manualmente de maneira simples:

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

Tags