Today’s task is to copy a database backup off of a network share and restore it locally. So to start we’re copying from a network share to the local host.
$dbName = “MyDBName”
$RemotePath = "\\MyServer\Backup$\" + $dbName + "\"
That puts $RemotePath at a point where I have a variable with the folder that I want. Now test that it works and I have connectivity with a Get-ChildItem
Get-ChildItem $RemotePath
I received results back, so lets filter that down to 7zipped files.
Get-ChildItem $RemotePath –filter “*.7z”
This is good, but I should probably account for if someone decides they want to hide the backup files or something silly like that.
Get-ChildItem $RemotePath –force –filter “*.7z”
That all works, now to sort those files by LastWriteTime
(Thanks StackOverflow for this handy sort)
Get-ChildItem $RemotePath –force –filter “*.7z” | sort @{expression={$_.LastWriteTime}; Descending=$true}
That sorted the list fine, now to select just that last one and only its name.
Get-ChildItem $RemotePath –force –filter “*.7z” | sort @{expression={$_.LastWriteTime}; Descending=$true} | select Name -first 1
And wrapped into a function
function GetLastItem()
{
param([string]$RemotePath)
$returnString = Get-ChildItem $RemotePath -force -filter "*.7z" | sort @{expression={$_.LastWriteTime}; Descending=$true} | select Name -first 1
return $returnString.Name
}
So to use this
$filename = GetLastItem $RemotePath
$RemoteFile = $RemotePath + $filename
Monday, February 21, 2011
Get the most recently written file out of a network share directory with PowerShell
Labels:
powershell,
script
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment