0
votes

When you try to execute a file in powershell, ie .\file, it seems like it executes it as though through the Invoke-Item cmdlet. Is it possible to override, replace, or augment this functionality within my powershell profile? I'd like to be able to replace the inspection by extension/user prompt default open behavior with something more intelligent by default.

1
Can you provide an example? and is there a reason that you can't change the default file association? - HAL9256
For example, If I wanted to change how the file is executed based on its contents or metadata. At the most basic level, like how the shebang line works in linux would be nice, files whose first line can determine how they're executed. I't be nice if I could have a system flexible enough so I could specify checks like 'if the file is a zip file less than so many mb extract to current directory and cd'. I know I can check all these things in powershell, I just can't figure out how to hook into the actual invocation of the object to override the default call. - Wesley Wigham

1 Answers

0
votes

The canonical way for solving a problem like that in Windows would be to change the default action for the type in question to a custom script/program that implements the logic you want applied to files of that type.

Changing the action can easily be done by adding changing a couple registry entries. Example for zip files:

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\CompressedFolder\shell]
;change default action
@="Open2"

[HKEY_CLASSES_ROOT\CompressedFolder\shell\Open2]
;change label of this action
@="My Custom Action"

[HKEY_CLASSES_ROOT\CompressedFolder\shell\Open2\command]
;command for this action
@="powershell.exe -File \"C:\path\to\zip-handler.ps1\" \"%1\""

The script could (for instance) look like this:

$zip = Get-Item $args[0]

if ($zip.Length -le 10MB) {
  [Reflection.Assembly]::LoadWithPartialName('System.IO.Compression.FileSystem') | Out-Null
  $targetFolder = Split-Path -Parent $zip.FullName
  [IO.Compression.ZipFile]::ExtractToDirectory($zip.FullName, $targetFolder)
} else {
  explorer.exe $zip.FullName
}