Review Request- How 2 Simplify

Hello All,

I originally hopped into the irc channel to find some direction 'cause I couldn’t figure out which way was sideways :frowning: To help exlpain what I am trying to accomplish, I posted this - After some direction given by jrich523, I put together the following solution I’m looking for ways to improve this, if any.

What this allows me to do is specify a remot server, a file name and remote file path like c$\filepath so a search for that file name will recursively be put together. Then the directory structure concerning all instances of the specified file name on the remote server will be created on my local server. Once the directories are created, the instances of the file name on the remote server are copied to the local server. I’m looking fwd to finding out if something more simple can achieve the same thing =)




kind of hard to read and understand your request, however maybe this is something you could work with:

$servername = "s002" $remotepath = "c:\temp" $remotefile = "file.txt" $localpath = "c:\temp2" $script = [scriptblock]::Create("get-childitem -Path $remotepath -Recurse -filter $remotefile") $remoteFiles = invoke-command -ComputerName $servername -ScriptBlock $script $remotefiles | foreach { $destinationPath = $localpath + ($ -replace "$($_.psdrive):", "") New-Item -path $destinationPath -ItemType directory | Out-Null Copy-Item -Destination $destinationPath -Path "\\$servername\$($_.fullname.replace(":","$"))" } $remotefiles | select-object Name, Directory, PScomputername

I don’t know if it is any better/simpler you will have to judge about that, however I think it will be faster using invoke-command compared to relying on searching by UNC-path.

You may also create the scriptblock by doing:

$script = [scriptblock]“get-childitem -Path $remotepath -Recurse -filter $remotefile”

Also please use full cmdlet names and as little use of aliases as possible. Think of the next guy reading your scripts :slight_smile:



Hi Tore,

Thank you very much for taking the time to respond. I’m somewhat new to powershell & am also not accustomed to ‘best practices’ when posting examples. I’ll do better with the non-alias stuff going forward; good suggestion. I’ve not had a need to look into what scriptblock’s purpose is or how it works. While speed is not a primary factor in this particular case, by default I prefer to optimize for efficiency & speed, and those two factors seem to go hand in hand from what I can tell so far.

I will take your solution and see how it functions in my environment. I’ll try 'n update some time later.