Home > Software engineering >  How receive url address indicated by .url shortcuts with powershell
How receive url address indicated by .url shortcuts with powershell

Time:11-11

I need copy pdf files between Source and Destination server, but pdf files are stored on Source server only as shortcuts to web address (FileName.pdf.url files).

Network source/destination shares mapped as disk D: and E:

Copy-Item -Path D:\FileName.pdf.url -Destination E:\FileName.pdf 

copy only .url shortcut, I need copy pdf file.

When I open properties of file by Windows explorer in 'Web Content' tab visible is URL address. For example https://ServerName.int:11443/AFUWeb/RetrieveDocument.do?r=ieXZcv-OHZHB465.pdf.

powershell 5.1 w2k12

How received URL info from powershell level.

Get-ChildItem, Get-ItemProperty doesn't received this information for .url files

I found out how download pdf file from remote server, but need pdf web address to provide URL address as variable for 'DownloadFile' as below

$NewFile = New-Object System.Net.WebClient
$NewFile.DownloadFile("**https://ServerName.int:11443/AFUWeb/RetrieveDocument.do?r=ieXZcv-OHZHB465.pdf**","C:\Temp\test.pdf")
$NewFile = New-Object System.Net.WebClient
$NewFile.DownloadFile("**$URLVariable**","C:\Temp\FileName.pdf")

CodePudding user response:

  • Use the WScript.Shell (WshShell) COM object's .CreateShortcut() method to extract the target URL from your URL shortcut file (.url)

    • Note: Despite the method's name, it can also read existing shortcut (.lnk) and URL shortcut (.url) files, as WshShortcut and WshUrlShortcut instances, respectively; in the latter case, unfortunately, the target URL is the only property of the shortcut that can be retrieved, via .TargetPath (aside from .FullPath, the file's full path).
  • It's easier to use PowerShell's Invoke-WebRequest cmdlet to download the file.

# Note: Be sure to use a *full path*
$url = 
  (New-Object -ComObject WScript.Shell).CreateShortcut('D:\FileName.pdf.url').TargetPath

Invoke-WebRequest $url -OutFile C:\Temp\FileName.pdf

CodePudding user response:

I assume that your .url file contains a content like this:

[InternetShortcut] URL=https://ServerName.int:11443/AFUWeb/RetrieveDocument.do?r=ieXZcv-OHZHB465.pdf

Then you could get the content of the file and use regex to get the URL value. When the naming of the source files is consistent, you can use the BaseName Property of Get-Childitem for the filename in destination.

# Get all .url files
$Source = "D:\"
$UrlFiles = Get-ChildItem -File -Path $Source -Filter "*.url*"

# Get file content, extract URL from each file and download it
foreach ($UrlFile in $UrlFiles) {
    $Content = Get-Content $UrlFile.FullName -Raw
    $URL = [regex]::Match($Content,"(?<=\=).*").Value
    $SaveTo = "E:\$($UrlFile.BaseName)"

    $NewFile = New-Object System.Net.WebClient
    $NewFile.DownloadFile($URL,$SaveTo)
}
  • Related