大家下午好!
使用我的同事使用的脚本,我们将很多工作移到了Sharepoint,目的是提供一种简单的方法将文件设置为只读并使用内置的NTFS压缩进行压缩。 / p>
所有这些都可以像下面的代码一样正常运行。我需要解决的问题是,我需要以某种方式将工作程序在文件资源管理器中打开的当前目录传递给“打开文件”对话框。这样,当脚本运行时,您不必手动将其更改为正确的位置。
当前,我已将其设置为在用户桌面目录上打开
这可能吗?
谢谢
Add-Type -AssemblyName System.Windows.Forms
$FileBrowser = New-Object System.Windows.Forms.OpenFileDialog -Property @{
InitialDirectory = [Environment]::GetFolderPath('Desktop')
Multiselect = $true # Multiple files can be chosen
}
[void]$FileBrowser.ShowDialog()
$path = $FileBrowser.FileNames;
If($FileBrowser.FileNames -like "*\*") {
# Do something before work on individual files commences
$FileBrowser.FileNames #Lists selected files (optional)
foreach($file in Get-ChildItem $path){
Get-ChildItem ($file) |
ForEach-Object {
Set-ItemProperty -Path $path -Name IsReadOnly -Value $true
compact /C $_.FullName
}
}
# Do something when work on individual files is complete
}
else {
Write-Host "Cancelled by user"
}
答案 0 :(得分:0)
以下解决方案确定最顶文件浏览器窗口(Z顺序中最高的窗口)打开的目录。
也就是说,如果文件资源管理器本身是活动的,则使用该活动窗口的目录,否则为最近活动的窗口的目录。
# Helper type for getting windows by class name.
Add-Type -Namespace Util -Name WinApi -MemberDefinition @'
// Find a window by class name and optionally also title.
// The TOPMOST matching window (in terms of Z-order) is returned.
// IMPORTANT: To not search for a title, pass [NullString]::Value, not $null, to lpWindowName
[DllImport("user32.dll")]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
'@
# Get the topmost File Explorer window, by its class name.
$hwndTopMostFileExplorer = [Util.WinApi]::FindWindow(
"CabinetWClass", # the window class of interest
[NullString]::Value # no window title to search for
)
if (-not $hwndTopMostFileExplorer) {
Write-Warning "There is no open File Explorer window."
# Alternatively, use a *default* directory in this case.
return
}
# Using a Shell.Application COM object, locate the window by its hWnd and query its location.
$fileExplorerWin = (New-Object -ComObject Shell.Application).Windows() |
Where-Object hwnd -eq $hwndTopMostFileExplorer
# This should normally not happen.
if (-not $fileExplorerWin) {
Write-Warning "The topmost File Explorer window, $hwndTopMostFileExplorer, must have just closed."
return
}
# Determine the window's active directory (folder) path.
$fileExplorerDir = $fileExplorerWin.Document.Folder.Self.Path
# Now you can use $fileExplorerDir to initialize the dialog:
Add-Type -AssemblyName System.Windows.Forms
$FileBrowser = New-Object System.Windows.Forms.OpenFileDialog -Property @{
InitialDirectory = $fileExplorerDir
Multiselect = $true # Multiple files can be chosen
}
$null = $FileBrowser.ShowDialog()
# ...