在变量中的多行中添加相同的行

时间:2017-08-11 11:32:30

标签: powershell powershell-v3.0

我有以下PowerShell脚本来获取从特定时间创建的文件:

$diff = "H:\DBBackup\server1\queryDB\Diff\"
$tlogs = "H:\DBBackup\server1\queryDB\trn\"

$compareDate = Get-Date (Get-Item $diff).LastWriteTime

$trn = Get-ChildItem -Path $tlogs | Where-Object {
    $_.LastWriteTime -gt $compareDate -and !($_.PSIsContainer)
} | Sort-Object LastWriteTime

$trn.Name

以下是上述脚本的输出

SQLSLinuxServerDB_backup_2017_08_10_043503_8807816.trn
SQLSLinuxServerDB_backup_2017_08_10_044003_8906811.trn
SQLSLinuxServerDB_backup_2017_08_10_053903_4501615.trn
SQLSLinuxServerDB_backup_2017_08_11_032503_7408313.trn
SQLSLinuxServerDB_backup_2017_08_11_043003_7803417.trn
SQLSLinuxServerDB_backup_2017_08_11_044003_2408719.trn

现在我想使用$tlog中添加的路径的上述值来运行上面脚本中的命令。

ascp -T -l 100m -m 10m -i "C:\Users\abc\.ssh\id_putty.ppk" H:\DBBackup\server1\queryDB\trn\SQLSLinuxServerDB_backup_2017_08_10_043503_8807816.trn test@192.168.22.156:/SQLSLinuxServerDB_backup_2017_08_10_043503_8807816.trn
ascp -T -l 100m -m 10m -i "C:\Users\abc\.ssh\id_putty.ppk" H:\DBBackup\server1\queryDB\trn\SQLSLinuxServerDB_backup_2017_08_10_044003_8906811.trn test@192.168.22.156:/SQLSLinuxServerDB_backup_2017_08_10_044003_8906811.trn
ascp -T -l 100m -m 10m -i "C:\Users\abc\.ssh\id_putty.ppk" H:\DBBackup\server1\queryDB\trn\SQLSLinuxServerDB_backup_2017_08_10_053903_4501615.trn test@192.168.22.156:/SQLSLinuxServerDB_backup_2017_08_10_053903_4501615.trn
ascp -T -l 100m -m 10m -i "C:\Users\abc\.ssh\id_putty.ppk" H:\DBBackup\server1\queryDB\trn\SQLSLinuxServerDB_backup_2017_08_11_032503_7408313.trn test@192.168.22.156:/SQLSLinuxServerDB_backup_2017_08_11_032503_7408313.trn
ascp -T -l 100m -m 10m -i "C:\Users\abc\.ssh\id_putty.ppk" H:\DBBackup\server1\queryDB\trn\SQLSLinuxServerDB_backup_2017_08_11_043003_7803417.trn test@192.168.22.156:/SQLSLinuxServerDB_backup_2017_08_11_043003_7803417.trn
ascp -T -l 100m -m 10m -i "C:\Users\abc\.ssh\id_putty.ppk" H:\DBBackup\server1\queryDB\trn\SQLSLinuxServerDB_backup_2017_08_11_044003_2408719.trn test@192.168.22.156:/SQLSLinuxServerDB_backup_2017_08_11_044003_2408719.trn

有没有办法在我的PowerShell脚本中使用字符串或变量而不是硬编码来使用上面的命令。

我试过这个

$LatestDiffFile = $tlogs + $trn.Name
$LatestDiffFile

但这不符合我的想法。

1 个答案:

答案 0 :(得分:1)

要获取最新,在LastWriteTime上排序后,抓取-1数组中的最后一个索引($trn):

$LatestDiffFile = $tlogs + $trn[-1].Name

如果您想在$tlogs中将$trn添加到所有名称并发出ascp命令,请使用循环:

foreach($file in $trn){
    # Construct local file path
    $LocalPath = Join-Path $tlogs $file.Name
    # Construct remote file path
    $RemotePath = 'test@192.168.22.156:/{0}' -f $file.Name
    # Prepare ascp arguments
    $ascpArgs = '-T -l 100m -m 10m -i "C:\Users\abc\.ssh\id_putty.ppk"',$LocalPath,$RemotePath

    # Execute
    & ascp $ascpArgs
}