title: Getting any special folder path in Powershell using folder GUID
body: <p>I want to use a PowerShell script to automate tasks related to the user when the user logs in.</p>
  
  <p>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?</p>
  
  <p>I tried to use SHGetKnownFolderPath calls from PowerShell based on <a href="http://www.leeholmes.com/blog/2009/01/19/powershell-pinvoke-walkthrough" rel="nofollow">Lee Holmes work</a></p>
  
  <p>As pinvoke website C# sample doesn't use StringBuilder, I assumed it was not required and stripped builder + "-Using" references</p>
  
  <pre class="lang-powershell prettyprint-override"><code>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) 
  </code></pre>
  
  <p>I also tried to use New-PInvoke from <a href="http://poshcode.org/1409" rel="nofollow">here</a> 
  with "shell32.dll" as lib value and </p>
  
  <pre class="lang-powershell prettyprint-override"><code>int SHGetKnownFolderPath(     [MarshalAs(UnmanagedType.LPStruct)] Guid rfid,     uint dwFlags,     IntPtr hToken,     out String pszPath  )
  </code></pre>
  
  <p>as signature value, then using from powershell</p>
  
  <pre class="lang-powershell prettyprint-override"><code>SHGetKnownFolderPath FDD39AD0-238F-46AF-ADB4-6C85480369C7 0 0 [ref]$path
  </code></pre>
  
  <p>I ends with this error</p>
  
  <pre class="lang-none prettyprint-override"><code>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
  </code></pre>
  
  <p>I don't understand where I got wrong on both trials.</p>
  
  <p><strong>SOLUTION:</strong><br>
  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 !</p>