簡體   English   中英

如何使用 powershell 調用 SHGetKnownFolderPath?

[英]How can I use powershell to call SHGetKnownFolderPath?

我是 windows powershell 的完全菜鳥。 如何使用 psl 調用 SHGetKnownFolderPath ? 如果我不喜歡 Get 調用返回的某些值,我還想調用 SHSetKnownFolderPath。

您可以使用 P/Invoke。 李福爾摩斯有如何做到這一點從PowerShell的一個例子在這里 還有如何使用的例子SHGetKnownFolderPoath這里

或者,您可能只能使用Environment.GetFolderPath

PS> [Environment]::GetFolderPath('CommonApplicationData')
C:\ProgramData

您可以通過以下方式獲取可用選項列表:

PS> [Enum]::GetNames([Environment+SpecialFolder])

在深入研究 Framework 中的靜態方法之前,先看看Env: PSDrive中的變量。

get-childitem env:

(get-item env:\\CommonProgramFiles).Value

根據本教程(和其他教程),設置在注冊表中:

[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders]
[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders]

這些在powershell 中很容易閱讀,將它們作為驅動器訪問:

ps> cd hkcu:\Software\Microsoft\Windows\CurrentVersion\Explorer\
ps> dir

並使用標准的powershell工具讀取這些設置。

注意:您可以在此處使用 powershell 設置它們,但這可能會毀了您的一天。

如果您使用資源管理器更改目錄,它還會移動目錄並將設置存儲在多個位置,例如“用戶外殼文件夾”和“外殼文件夾”。

這是一個您可以使用的函數,它將使用 SHGetKnownFolderPath 將眾所周知的文件夾 guid 轉換為其當前路徑:

Function GetKnownFolder([string]$KnownFolderCLSID) {
  $KnownFolderCLSID = $KnownFolderCLSID.Replace("{", "").Replace("}", "")
  $GetSignature = @'
    [DllImport("shell32.dll", CharSet = CharSet.Unicode)]public extern static int SHGetKnownFolderPath(
    ref Guid folderId, 
    uint flags, 
    IntPtr token,
    out IntPtr pszProfilePath);
'@
  $GetType = Add-Type -MemberDefinition $GetSignature -Name 'GetKnownFolders' -Namespace 'SHGetKnownFolderPath' -Using "System.Text" -PassThru -ErrorAction SilentlyContinue
  $ptr = [intptr]::Zero
  [void]$GetType::SHGetKnownFolderPath([Ref]"$KnownFolderCLSID", 0, 0, [ref]$ptr)
  $result = [System.Runtime.InteropServices.Marshal]::PtrToStringUni($ptr)
  [System.Runtime.InteropServices.Marshal]::FreeCoTaskMem($ptr)
  return $result
}

用法示例:

GetKnownFolder "C4AA340D-F20F-4863-AFEF-F87EF2E6BA25"

將返回

C:\Users\Public\Desktop

可以在Microsoft找到有關眾所周知的文件夾 GUID 的參考

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM