How To Pin To Start Special Folders With No Target - c#

How do you pin to start special folders using powershell? Like "ThisPC", iexplorer
This will pin to start exe's fine, but what about windows explorer and myComputer? How to pin those items since they have no target?
Given this
<start:DesktopApplicationTile Size="2x2" Column="0" Row="0" DesktopApplicationLinkPath="%APPDATA%\Microsoft\Windows\Start Menu\Programs\Windows System\This PC.lnk" />
It seems to have issues with .lnk's for "This PC", "File Explorer", etc
Function PinLnk
{
Param
(
[Parameter(Mandatory,Position=0)]
[Alias('p')]
[String[]]$Path
)
$Shell = New-Object -ComObject Shell.Application
$Desktop = $Shell.NameSpace(0X0)
$WshShell = New-Object -comObject WScript.Shell
$Flag=0
Foreach($itemPath in $Path)
{
$itemName = Split-Path -Path $itemPath -Leaf
#pin application to windows Start menu
$ItemLnk = $Desktop.ParseName($itemPath)
$ItemVerbs = $ItemLnk.Verbs()
Foreach($ItemVerb in $ItemVerbs)
{
If($ItemVerb.Name.Replace("&","") -match "Pin to Start")
{
$ItemVerb.DoIt()
$Flag=1
}
}
}
}
PinLnk "C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\devenv.exe"
I tried this approach as well still not pinning mycomputer to start
PS C:\WINDOWS\system32> Function PinLnk14
>> {
>>
>> $shell = new-object -com Shell.Application
>> $folder = $shell.NameSpace("shell:::{20D04FE0-3AEA-1069-A2D8-08002B30309D}") # ssfDRIVES
>> $ItemVerbs=$folder.Self.Verbs()
>> Foreach($ItemVerb in $ItemVerbs)
>> {
>> Write-Output $ItemVerb.Name
>> If($ItemVerb.Name.Replace("&","") -match "Pin to Start")
>> {
>> Write-Output "TRYING TO PIN"
>> $ItemVerb.DoIt()
>> }
>> }
>> }
PS C:\WINDOWS\system32>
PS C:\WINDOWS\system32> Pinlnk14
&Open
Pin to Quick access
Mana&ge
&Pin to Start
TRYING TO PIN
Map &network drive...
Dis&connect network drive...
Create &shortcut
&Delete
Rena&me
P&roperties

Most special folders are accessible using special values, documented here: ShellSpecialFolderConstants enumeration
So, if you want to get the My Computer (a.k.a. "This PC") folder, you can do this:
$shell = new-object -com Shell.Application
$folder = $shell.NameSpace(17) # "ssfDRIVES" constant
And this will get you a Folder object.
There is another way wich uses the folder CLSID (a guid). It will allow you to get to any folder in what's called the shell namespace, even the ones that may not be defined in the enumeration above (3rd party shell namespace extensions for example). The syntax is this:
$shell = new-object -com Shell.Application
$folder = $shell.Namespace("shell:::{CLSID}")
In fact, this funny syntax combines the 'shell:' URI moniker with the shell namespace parsing syntax ::{CLSID}.
So for example to get the My Computer folder, you would do use the constant known as CLSID_MyComputer like this:
$shell = new-object -com Shell.Application
$folder = $shell.Namespace("shell:::{20D04FE0-3AEA-1069-A2D8-08002B30309D}")
This will also work:
$shell = new-object -com Shell.Application
$folder = $shell.Namespace("shell:MyComputerFolder") # direct shell: syntax
And it should bring you back the same object as in the previous call. They're all equivalent.
Once you have a Folder object, there is a last trick to get the associated verbs, because the Verbs() method is only defined on the FolderItem object.
To get the FolderItem from the Folder (as a Folder is also an "item" in the namespace, so it has also a FolderItem facade), you can use the Self property, like this:
$shell = new-object -com Shell.Application
$folder = $shell.NameSpace("shell:::{20D04FE0-3AEA-1069-A2D8-08002B30309D}") # ssfDRIVES
$folder.Self.Verbs()
Ok, that was to get verbs for a FolderItem. To pin an item to start however, the "Pin to Start" verb invocation does not always work (for My Computer for example), or the verb isn't even available (for a standard folder for example). In general, it doesn't really work well for folders for some reason.
So, one solution for folders is to first create a shortcut file (.lnk) somewhere to that folder (including My Computer or other special locations), and pin that shortcut file to start. Note: the standard (non language localized) verb for Pin to Start is "PinToStartScreen", it's better to use that than to scan various verbs (all verbs have a canonical name). So the code would look like this to pin My Computer to start:
$wshell = new-object -com WScript.Shell
$shortcut = $wshell.CreateShortcut("c:\temp\mypc.lnk")
$shortcut.TargetPath = "shell:MyComputerFolder" # use the same syntax as described above
$shortcut.Save()
$shell = new-object -com Shell.Application
$folder = $shell.NameSpace("c:\temp")
$lnk = $folder.ParseName("mypc.lnk") # get the shortcut file
$lnk.InvokeVerb("PinToStartScreen") # invoke "Pin To Start" on the shortcut file
The fact is that's exactly what Windows does when we do "Pin to Start" on My Computer, it creates a shortcut in C:\Users\<my user>\AppData\Roaming\Microsoft\Windows\Start Menu\Programs

Related

How to open SolidWorks sldprt files as read-only with PowerShell?

I built this open-file function in PowerShell for a GUI I wrote that lets you find and open various files on a server. I mainly use it for opening SolidWorks files as read-only, but also for PDF files and it should work for just about any other file if there is a file association for it.
The problem is that sometimes it doesn't work when opening the sldprt files. SolidWorks will either ignore the open file request or it wont open as read-only. I think this is mostly just a solidworks issue as sometimes it wont open files when double clicked on from windows explorer.
Anyway my solution is to set the file attribute to read-only. start a job that opens the file in SolidWorks, and then waits for the SolidWorks process to go idle before removing the read-only attribute. It does this through an event that watches for the job state to change. Since this is running through a GUI it has to be done in the background to prevent the GUI from locking up.
Is there a simpler way to open files as read-only with PowerShell?
I think it might be possible using the SolidWorks .dll files, but they are meant to be loaded in C# or VB-script and I have no idea what i'm doing in either of those languages.
function open-File{
param(
[parameter(Mandatory=$true)]$file,
[bool]$readOnly = $true,
$processName=$null
)
[scriptblock]$openFileScriptBlock = {
param(
$file,
$readOnly,
$processName=$null
)
#initiate variables
$loaded = $false
$file = get-item $file
$processLastCpu = 0
$timeout = 0
if ($readonly -and !$file.isReadOnly){
$file.isReadOnly = $true
#call file with default application
$attempts = 0
while ($true){
try{$startedProcess = start-process "$($file.fullname)" -PassThru; break}
catch{
$attempts++
if ($attempts -eq 3){return "cannot open file: $file, Error:$_"}
}
}
start-sleep -seconds 2
if ($processName){
$processName = $startedProcess.name
if ($processName -eq "SWSHEL~1"){$processName = "SLDWORKS"}
}
#wait until process shows up in the process manager
while ($loaded -eq $false -and $timeout -lt 25 ){
try {
$process = get-process -name $processName -erroraction 'stop'
if ($?){$loaded = $true; $timeout = 0} else {throw}
}catch{start-sleep -milliseconds 200; $timeout++}
}
start-sleep -seconds 2
#wait for process to go idle
while ($process.cpu -ne $processLastCpu -and $timeout -lt 10){
$processLastCpu = $process.cpu
start-sleep -milliseconds 500
$timeout++
}
$file.isreadonly = $false
} else {start-process "$($file.fullname)"}
return ,$file
}
if (!(test-path -path $file)){update-message "File not found: $file"; return}
$openFileJob = start-job -name 'openfile' -scriptblock $openFileScriptBlock -argumentlist $file, $readOnly, $processName
Register-ObjectEvent $OpenFileJob StateChanged -Action {
$jobResult = $sender | receive-job
$sender | remove-job -Force
unregister-event -sourceIdentifier $event.sourceIdentifier
remove-job -name $event.sourceIdentifier -force
try{update-message "opened file $($jobResult.name)"}
catch{update-message $jobResult}
} | out-null
}
I know its a old question, but i was wondering if you ever managed to get a solution?
If not, there is a few things you could try: first off, if your code is opening any other file just fine, it does not seem to be there the problem is.
File association with all SLD-files are working most of the time; but we do see it going bad from time to time (often related to updates), in that case, double-check that all SLD-file types are set to open with 'Solidworks-Launcher' (and not Solidworks directly).
Using the launcher, will ensure Solidworks does not try to open a file, into an already running instance of Solidworks.
Also, try to check the following: Solidworks Options -> Collaboration ->
'Enable Multi-user environments'... is this set?
whatever state it is in; try changing is to the opposite.
That checkmark is allowing multiple Solidworks-users to open the same file at the same time, and it does so by changing the read-state of the file, back and fourth.
(it could be it is interfering with your code)
Both of these things will be PC-specific, so if you change them on one machine, they might also need to be changed on other machines.

PowerShell Set Drive Labels Persisting And Unchangeable Until Reboot

Our software needs to map a network drive depending on which database the User logs in to.
The software first checks that the drive isn't already mapped, if it is then it skips the mapping step.
If the drive isn't mapped, or it is mapped to a different share (i.e. the User was previously logged in to a different database), then it clears any existing drive mapping, and maps the required drive.
It does this by generating and then running a PowerShell script.
Remove-SmbMapping -LocalPath "R:" -Force -UpdateProfile;
Remove-PSDrive -Name "R" -Force;
net use "R" /delete /y;
$password = ConvertTo-SecureString -String "Password" -AsPlainText -Force;
$credential = New-Object System.Management.Automation.PSCredential -ArgumentList "Username", $password;
New-PSDrive -Name "R" -PSProvider "FileSystem" -Root "\\server\share" -Credential $credential -Persist;
$a = New-Object -ComObject shell.application;
$a.NameSpace( "R:" ).self.name = "FriendlyName";
The first three lines remove any existing mapping on that drive letter. They all theoretically do the same thing, however thanks to Microsoft it's entirely random which line will actually work. It only consistently works if all three lines are run.
The middle three lines map the new drive.
The last two lines change the drive label of the new drive to something more user-friendly than the default \\server\share label
The first time someone logs in after a reboot the above script works perfectly. The new drive is mapped, and the label is changed.
However, if the User then logs out and logs into a different database, the label will not change.
For example, the User first logs in to 'Database A', and the drive is mapped with the label 'DatabaseAFiles'. All well and good.
But if the User then logs out, and logs in to 'Database B', the drive is correctly mapped and points to the correct share, but the label still says 'DatabaseAFiles' and not 'DatabaseBFiles'.
If the User reboots their PC, however, and logs in to 'Database B', then the label will correctly say 'DatabaseBFiles', but any subsequent log ins to other databases again won't change the label.
Reboot
Log in to Database A, label is DatabaseAFiles
Log out and into Database B, label is still DatabaseAFiles
Reboot
Log in to Database B, label is now DatabaseBFiles
This is not dependent on the last two script lines being present (the two that set the label), I actually added those to try to fix this issue. If those two lines are removed, the label is the default \\server\share label, and still doesn't change correctly, i.e.
Reboot
Log in to Database A, label is \\servera\sharea
Log out and into Database B, label is still \\servera\sharea
Reboot
Log in to Database B, label is now \\serverb\shareb
Regardless of the label, the drive is always correctly mapped to the correct share, and using it has all the correct directories and files.
Everything works correctly, it's just the label that is incorrect after the first login per reboot.
The script is run from within a C# program in a created PowerShell instance
using (PowerShell PowerShellInstance = PowerShell.Create())
{
PowerShellInstance.AddScript(script);
IAsyncResult result = PowerShellInstance.BeginInvoke();
while (result.IsCompleted == false)
{
Thread.Sleep(1000);
}
}
As it maps a drive, it cannot be run in Adminstrator mode (the drive won't be mapped for the actual User), it has to be run in normal mode, so there is a check earlier up for that.
If I take a copy of the script and run it in a PowerShell session outside the C# program, I get exactly the same results (everything works but the label is wrong after the first login), so it's not that it's being run from within the C# program.
It's entirely possible that the issue is with either File Explorer or with Windows, either caching the label somewhere and reusing it could be the problem, of course.
Anyone have any suggestions of things I can try please?
A time ago, I have had to rename file shares and therefor I wrote this function. Maybe this is helpful for you.
#--------------------------------------
function Rename-NetworkShare {
#--------------------------------------
param(
[string]$sharePattern,
[string]$value
)
$regPath = Get-ChildItem 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\MountPoints2'
$propertyName = '_LabelFromReg'
foreach( $child in $regPath ) {
if( $child.PSChildName -like ('*' + $sharePattern + '*') ) {
if( !$child.Property.Contains( $propertyName ) ) {
New-ItemProperty $child.PSPath -Name $propertyName -PropertyType String | Out-Null
}
Set-ItemProperty -Path $child.PSPath -Name $propertyName -Value $value | Out-Null
}
}
}
Rename-NetworkShare -sharePattern 'patternOldName' -value 'NewFriendlyName'
It's not ideal, there's one bit I'm not happy about, but this is the best I've been able to come up with so far. If I come up with something better I'll post that instead.
Firstly, I check if there is already a drive mapped to the letter I want to use:-
// Test if mapping already exists for this database
var wrongMapping = false;
var drives = DriveInfo.GetDrives();
foreach (var drive in drives)
{
var driveLetter = drive.RootDirectory.ToString().Substring(0, 1);
if (driveLetter == mappingDetails.DriveLetter && Directory.Exists(drive.Name))
{
wrongMapping = true; // Assume this is the wrong drive, if not we'll return from the method before it's used anyway
var unc = "Unknown";
using (RegistryKey key = Registry.CurrentUser.OpenSubKey("Network\\" + driveLetter))
{
if (key != null)
{
unc = key.GetValue("RemotePath").ToString();
}
}
if (unc == mappingDetails.Root)
{
View.Status = #"Drive already mapped to " + mappingDetails.DriveLetter + ":";
ASyncDelay(2000, () => View.Close());
return; // Already mapped, carry on with login
}
}
}
If we already have the correct path mapped to the correct drive letter, then we return and skip the rest of the mapping code.
If not, we'll have the variable wrongMapping, which will be true if we have a different path mapped to the drive letter we want. This means that we'll need to unmap that drive first.
This is done via a Powershell script run the by C# program, and contains the bit I'm not happy about:-
Remove-PSDrive mappingDetails.DriveLetter;
Remove-SmbMapping -LocalPath "mappingDetails.DriveLetter:" -Force -UpdateProfile;
Remove-PSDrive -Name "mappingDetails.DriveLetter" -Force;
net use mappingDetails.DriveLetter /delete /y;
Stop-Process -ProcessName explorer;
The first four lines are different ways to unmap a drive, and at least one of them will work. Which one does work seems to be random, but between all four the drives (so far) always get unmapped.
Then we get this bit:
Stop-Process -ProcessName explorer;
This will close and restart the Explorer process, thus forcing Windows to admit that the drive we just unmapped is really gone. Without this, Windows won't fully release the drive, and most annoyingly it will remember the drive label and apply it to the next drive mapped (thus making a mapping to CompanyBShare still say CompanyAShare).
However, in so doing it will close any open File Explorer windows, and also briefly blank the taskbar, which is not good.
But, given that currently no Company sites have more than one share, and it's only the Developers and Support that need to remove existing drives and map new ones, for now we'll put up with it.
Once any old drive is unmapped, we then carry on and map the new drive, which again is done via a PowerShell script run from the C# code.
$password = ConvertTo-SecureString -String "mappingDetails.Password" -AsPlainText -Force;
$credential = New-Object System.Management.Automation.PSCredential -ArgumentList "mappingDetails.Username", $password;
New-PSDrive -Name "mappingDetails.DriveLetter" -PSProvider "FileSystem" -Root "mappingDetails.Root" -Credential $credential -Persist;
$sh=New_Object -com Shell.Application;
$sh.NameSpace('mappingDetails.DriveLetter:').Self.Name = 'friendlyName';
New-Item –Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\MountPoints2\" –Name "foldername";
Remove-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\MountPoints2\foldername" -Name "_LabelFromReg";
New-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\MountPoints2\foldername" -Name "_LabelFromReg" -Value "friendlyName" -PropertyType "String\";
The first part maps the drive:
$password = ConvertTo-SecureString -String "mappingDetails.Password" -AsPlainText -Force;
$credential = New-Object System.Management.Automation.PSCredential -ArgumentList "mappingDetails.Username", $password;
New-PSDrive -Name "mappingDetails.DriveLetter" -PSProvider "FileSystem" -Root "mappingDetails.Root" -Credential $credential -Persist;
The middle part changes the name directly:
$sh=New_Object -com Shell.Application;
$sh.NameSpace('mappingDetails.DriveLetter:').Self.Name = 'friendlyName';
And the end part changes the name in the Registry:
New-Item –Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\MountPoints2\" –Name "foldername";
Remove-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\MountPoints2\foldername" -Name "_LabelFromReg";
New-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\MountPoints2\foldername" -Name "_LabelFromReg" -Value "friendlyName" -PropertyType "String\";
Firstly, it creates a key for this path (it the key already exists it'll fail but the script will carry on)
Then it removes the existing property _LabelFromReg (if it doesn't exist it'll fail but the script will carry on)
Then it (re)creates the property _LabelFromReg with the new friendlyname.
So, again doing the same thing two ways, but between the two it works.
I'd like to find some alternative to having to kill and restart the Explorer process, it's really tacky, but it seems to be the only way to get Windows to acknowledge the changes.
And at least I now get the correct labels on the drives when mapped.

Powershell - Globally register IO.FileSystemWatcher

I've successfully created a FileSystemWatcher (C# object). I run the code below in a powershell session.
# Filters
$filter = "somefile.txt"
$flagfolder = "C:\path\to\some\folder"
# Instantiate Watcher
$Watcher = New-Object IO.FileSystemWatcher $flagfolder, $filter -Property #{
IncludeSubdirectories = $false
NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'
}
# EVENT: $filter is created
$onCreated = Register-ObjectEvent $Watcher Created -SourceIdentifier FileCreated -Action {
$path = $Event.SourceEventArgs.FullPath
$name = $Event.SourceEventArgs.Name
$changeType = $Event.SourceEventArgs.ChangeType
$timeStamp = $Event.TimeGenerated
Write-Host "The file '$name' was $changeType at $timeStamp"
Write-Host $path
someglobalfunction $param
}
After running the code above, if I do a Get-Job it reports the FileWatcher:
Id Name PSJobTypeName State HasMoreData Location
-- ---- ------------- ----- ----------- --------
74 FileCreated NotStarted False
But, if I open a new powershell session and do a Get-Job it reports nothing....
I need this to fire whenever anybody or anything creates the file $pathfolder\somefile.txt... but currently it only works when the session that defines $watcher creates the file.
You need two things to make this work.
New-Object System.IO.FileSystemWatcher
Register-ObjectEvent
I think this is the minimum code you need to make FileSystemWatcher work.
Set up the FileSystemWatcher object
$w = New-Object System.IO.FileSystemWatcher
$w.Path = $PWD
$PWD (current working directory) is an automatic variable.
Subscribe to the "Created" event (for simplicity)
Register-ObjectEvent -InputObject $w -EventName Created -SourceIdentifier "File.Created" `
-Action {Write-Host -Object "A file was created" -ForegroundColor Green -BackgroundColor Black}
Now, if you create a file in the current working directory, PowerShell will write "A file was created" to the screen. It doesn't matter how that file gets created--in the current session, in a different PowerShell session, through File Explorer, using cmd.exe--doesn't matter.
This answer has more elaborate code. But the simplified code here is based directly on it.

Loading a Powershell Module from the C# code of a custom Provider

I've been working on a VERY specific functionality "need" to tie into a custom Provider I'm writing in C#.
Basically I set out to find a way to replicate the
A:
B:
etc functions defined when PowerShell loads so instead of having to type
CD A:
You can just do the aforementioned
A:
I tried first to have my provider inject the functions into the runspace but it seems I'm completely missing the timing of how to get that to work so I went another route.
Basically I have a VERY simple PSM1 file UseColons.psm1
function Use-ColonsForPSDrives
{
[CmdletBinding()] Param()
Write-Verbose "Looping Through Installed PowerShell Providers"
Get-PSProvider | % `
{
Write-Verbose "Found $($_.Name) checking its drives"
$_.Drives | ? { (Get-Command | ? Name -eq "$($_.Name):") -eq $null } | `
{
Write-Verbose "Setting up: `"function $($_.Name):() {Set-Location $($_.Name):}`""
if ($Verbose)
{
. Invoke-Expression -Command "function $($_.Name):() {Set-Location $($_.Name):}"
}
else
{
. Invoke-Expression -Command "function $($_.Name):() {Set-Location $($_.Name):}" -ErrorAction SilentlyContinue
}
Write-Verbose "Finished with drive $($_.Name)"
}
}
# Cert and WSMan do not show up as providers until you try to naviagte to their drives
# As a result we will add their functions manually but we will check if they are already set anyways
if ((Get-Command | ? Name -eq "Cert:") -eq $null) { . Invoke-Expression -Command "function Cert:() {Set-Location Cert:}" }
if ((Get-Command | ? Name -eq "WSMan:") -eq $null) { . Invoke-Expression -Command "function WSMan:() {Set-Location WSMan:}" }
}
. Use-ColonsForPSDrives
In simple terms it loops through all loaded providers, then through all the drives of each provider, then it checks if the Function: drive contains a function matching the {DriveName}: format and if one is not found it creates one.
The psd1 file is nothing more than export all functions
This is stored in the %ProgramFiles%\WindowsPowerShell\Modules path under its own folder
And finally I have profile.ps1 under the %windir%\system32\windowspowershell\v1.0 directory that just does
Remove-Module UseColons -ErrorAction SilentlyContinue
Import-Module UseColons
So when I load PowerShell or the ISE if I want to get to say dir through the variables I can just call
Variable:
Or if I need to switch back to the registry
HKLM:
HKCU:
Which when you are working with multiple providers typing that CD over and over as you switch is just annoying.
Now to the problem I'm still working on developing the actual PowerShell provider this was originally intended for. But when I debug it the UseColons module loads BEFORE visual studio turns around and loads the new provider so if I manually remove and import the module again it does its thing and I have all my drive functions for my provider.
I wanted to know after that LONG explanation how can I either:
Setup my UseColons module to load LAST
Find a way to have my Custom Provider (technically a module since it has the provider AND custom Cmdlets) load the UseColons module when it initializes
I don't want to remove it from my standard profile because it is very helpful when I'm not working on the new provider and just tooling around using powershell for administrative stuff.
Hopefully someone can give me some ideas or point me in the direction of some good deeper dive powershell provider documentations and how-tos.
In your module manifest (.psd1), you have a DLL as the RootModule?
This is a horrible hack, and does not help for drives that get created in the future, but...
In your module manifest, instead of YourProvider.dll as the RootModule, use Dummy.psm1 instead (can be an empty file). Then, for NestedModules, use #( 'YourProvider.dll', 'UseColons' ). This allows the UseColons module to be loaded after YourProvider.dll. (Dummy will be last.)

PowerShell -WebClient DownloadFile Wildcards?

I want to copy multiple files from a SharePoint libary to a local directory.
It is possible to use Wildcards?
The following code is not working. But is there a way to use the WebClient and Wildcards?
(I must use the WebClient. It is not possible to use the SharePoint WebServices :-( )
$url = "http://mySharePoint/websites/Site/TestDocBib/*.jpg"
$path = "D:\temp\"
$WebClient = New-Object System.Net.WebClient
$WebClient.UseDefaultCredentials = $true
$WebClient.DownloadFile($url, $path)
No, sorry, you can't use wildcards with WebClient. It's not part of HTTP.
What about using WEBDAV?
c:\> copy \\my.sharepoint.site\sites\foo\doclib\*.jpg c:\temp\
If the client end (i.e. not sharepoint) is a server 2008+ platform, you'll need to add the "desktop experience" role and enable the "webclient" service. This is not the same thing as system.net.webclient; it's the HTTP/DAV network redirector service.
If you need to log in with different credentials, you can use this:
c:\> net use * "http://my.sharepoint.site/sites/foo/doclib" /user:foobar
mapped h: to ...
c:\> copy h:\*.jpg c:\temp
Hope this helps.
you can parse though the html of the list.
# dummy url - i've added allitems.aspx
$url = "http://mySharePoint/websites/Site/TestDocBib/allitems.aspx"
$path = "D:\temp\"
$dl_file = $path + "allitems.html"
$WebClient = New-Object System.Net.WebClient
$WebClient.UseDefaultCredentials = $true
$WebClient.DownloadFile($url, $dl_file)
once you've downloaded the file you can parse though the file - a quick google turned up that Lee Holmes had done most of it already:
http://www.leeholmes.com/blog/2005/09/05/unit-testing-in-powershell-%E2%80%93-a-link-parser/
the main bit you want is the regex:
$regex = “<\s*a\s*[^>]*?href\s*=\s*[`"']*([^`"'>]+)[^>]*?>”
I very quick hack - that may (or may not) work... but the gist is there :)
$test = gc $dl_file
$t = [Regex]::Matches($test, $regex, "IgnoreCase")
$i = 0
foreach ($tt in $t) {
# this assumes absolute paths - you may need to add the hostname if the paths are relative
$url = $tt.Groups[1].Value.Trim()
$WebClient = New-Object System.Net.WebClient
$WebClient.UseDefaultCredentials = $true
$WebClient.DownloadFile($url, $($path + $i + ".jpg"))
$i = $i + 1
}

Categories