I want to use a PowerShell script to automate tasks related to the user when the user logs in.
Sometimes a user will have moved his Documents folder from the default location. How can I determine the location of the user's Documents folder in PowerShell with a method that will work for all special folders?
I tried to use SHGetKnownFolderPath calls from PowerShell based on Lee Holmes work
As pinvoke website C# sample doesn't use StringBuilder, I assumed it was not required and stripped builder + "-Using" references
param($KNOWNFOLDERID)
$Pinvoke = @’
[DllImport("shell32.dll")]
public static extern int SHGetKnownFolderPath(
[MarshalAs(UnmanagedType.LPStruct)] Guid rfid,
uint dwFlags,
IntPtr hToken,
out String pszPath // API uses CoTaskMemAlloc
);
‘@
$type = Add-Type -MemberDefinition $Pinvoke
-Name Win32Utils -Namespace SHGetKnownFolderPath
-PassThru
$type::SHGetKnownFolderPath($KNOWNFOLDERID)
I also tried to use New-PInvoke from here with "shell32.dll" as lib value and
int SHGetKnownFolderPath( [MarshalAs(UnmanagedType.LPStruct)] Guid rfid, uint dwFlags, IntPtr hToken, out String pszPath )
as signature value, then using from powershell
SHGetKnownFolderPath FDD39AD0-238F-46AF-ADB4-6C85480369C7 0 0 [ref]$path
I ends with this error
Argument: '4' should be a System.Management.Automation.PSReference. Use [ref].
At line:1 char:56
+ New-Item Function:Global:SHGetKnownFolderPath -Value { [Microsoft.PowerShell.Com ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodException
+ FullyQualifiedErrorId : NonRefArgumentToRefParameterMsg
I don't understand where I got wrong on both trials.
SOLUTION:
Windows7Library binary found by Kayasax on codeplex works for lazy people like me, or David Heffernan 's scriptlet that allow more customization, but may need some handwork if you use custom special folders, but more customizable, both answers are valid !