One skill a day | It’s not a floating window, it’s better than a floating window, wrap your script with shortcuts

Matrix homepage recommendation

Matrix is ​​a minority writing community. We advocate sharing real product experience, experience and thinking with practical value. From time to time, we will select the highest-quality articles from Matrix to show the most authentic experiences and opinions from users.

The article represents the author’s personal point of view, and the minority only makes minor changes to the title and layout.


After my co-workers observed me boringly playing with PowerShell during my lunch break, the false impression of “someone with high technical skills” was gradually established. Therefore, occasionally a colleague who is close to me will ask me to help complete some complicated text or file operations in exchange for coffee. With my familiarity with PowerShell scripts, I got “coffee freedom” by accident. So when my colleague X sent a message asking for help, I said yes without hesitation.

He wanted me to batch rename about 300 video files. According to the screenshots he provided, the original filenames looked like this:

 VID20221005110210.mp4 VID_20170812061211.mp4 Video_20180111171112.mp4团建视频(2).mp4 VID20130104150926.MOV团建视频(1).mp4

His requirement is to rename all the video files to the form of年年年年-月月-日日.mp4 , that is, to complete hundreds of conversions from VID20221005110210.mp4 to 2022-10-05.mp4 . In addition, since the video library is still expanding, he hopes that I will not only teach him fish, but also teach him the method.

“Write a script, and then tell him how to use the script” was my first reaction. After more than ten minutes of copying and pasting, adjusting and testing, the PowerShell script that met its expectations was released. As you can see from this link , there are more than one hundred lines in total. The core idea is: for videos with irregular file names, use this script to read the earliest creation date; in other cases, use regular expressions to extract the date in the file name:

 $BaseName = $Leaf -replace '(VID_|VID|video_)(\d{4})(\d{2})(\d{2}).*', '$2-$3-$4'

But the real difficulty is not the script: it is much more troublesome than I imagined for someone who has never touched the concept of terminal and shell to learn to use script. Opening PowerShell, modifying execution policies, and cd commands are all so unfamiliar to him. He put forward his own idea: “Can you create a floating window like Baidu Netdisk, and drag files to the floating window to complete a certain operation?”

2022_12_04-17_43_29

Although I don’t feel how complicated it is to enter a few lines of commands when I open the terminal every day, if I can really create such a small floating window, it will not only be simple and convenient, but also save me a lot of trouble. Not to mention that with a little poking around, I discovered that there’s an easy way to do it: Windows shortcuts.

principle

I wrote an article on how to play Windows shortcuts before, and it has a small function that I didn’t mention: when you drag a file or directory to a shortcut, Windows will process the file or directory with the executable file pointed to by the shortcut. For example, when I drag D:\Code\GridMove folder to the VScode shortcut on the desktop, VScode will open this directory directly:

2022_12_12-18_37_48

The target bar of the shortcut is an executable file, and the item that the user drags to the shortcut will be used as the parameter of the executable file, so the above operation is equivalent to executing in the shell:

 code.exe D:\Code\GridMove

When the application supports this method of use, it will have the effect of opening the file or directory operated by the user with the corresponding software. In fact, it is also possible to directly drag the file to the exe file, but generally speaking, the exe is hidden in a deep directory of the system disk, and cannot be moved casually, and no one will move their ideas.

I wrote a simple application: EchoArgs.exe can display all the parameters passed to it line by line, as shown in the figure below, when we drag multiple items, Windows will pass the full path of the file or directory to this application one by one , in other words we are executing:

 EchoArgs.exe D:\Test\A.jpg D:\Test\BD:\Test\C.txt

image-20221212173609036

Shortcuts to scripts

The shortcut target to execute the PowerShell script D:\Script.ps1 should fill in:

 powershell.exe -ExecutionPolicy bypass -noprofile -nologo -file D:\Script.ps1

-nologo and -noprofile are to speed up the startup of PowerShell. Since PowerShell is restricted to execute unsigned scripts by default, we also need to specify the -ExecutionPolicy bypass parameter. In order to make the whole process more senseless, we can also adjust运行方式of the shortcut to be最小化.

image-20221212183909065

For PowerShell scripts that only use one parameter, no special adjustments are required. The files and directories dragged and dropped by the user will be passed to the script file, which is equivalent to executing in the shell:

 D:\Script.ps1 <文件或目录路径>

For example, I want to implement the following function: upload the picture dragged and dropped to the shortcut to Cloudflare R2, name it with a timestamp, and copy the Markdown link, just like Picgo, the script Script.ps1 can write these:

 param ( [Parameter()][string]$pics ) if ($pics -eq $null ) { break } if (Test-Path $pics -PathType Leaf){ $Key = Split-Path $pics -Leaf $Extension = $key.Split('.')[-1] $Time = Get-Date -Format 'yyyyMMddHHmmss' $DestPath = $Time + '.' + $Extension if ($Extension -notin 'jpeg', 'jpg', 'png', 'gif', 'svg', 'ico') { break } $Null = rclone.exe copyto $pics Obj:/image/$DestPath --log-file D:\rclone-uppic.log -v Set-Clipboard "![image](https://obj.example.com/image/$DestPath)" -Passthru } }

The upload to object storage operation uses rclone, and the script only needs to use two judgments to deal with the situation that the user dragged a directory or a non-image file.

For the requirements at the beginning of this article, we have to process hundreds of files at the same time, so we need to use loops. It is also more convenient to adjust. In this non-interactive situation, the parameters and other structures of the script are unnecessary. Only the core code is kept, and then use foreach($arg in $args) at the outermost edge. The general structure is as follows, The full script is here :

 $OutputEncoding = [console]::InputEncoding = [console]::OutputEncoding = New-Object System.Text.UTF8Encoding if ( ! $args) { break } foreach ( $arg in $args ) { # rename-it }

distribution

A shortcut is a binary file, and its attributes are the same on different computers. But in order for users who get this shortcut to use it directly, we need to make some adjustments to the path:

  1. Make sure起始位置is empty, so that PowerShell will work under the shortcut path;
  2. Use relative paths when referring to script files, i.e. use pwsh.exe … -file DragTome.ps1 .

Package shortcuts and scripts and tell recipients to move and copy scripts and shortcuts at the same time. In addition, the PowerShell script may be marked as unsafe by Windows. At this time, you need to right-click the script and check信任文件.

The demand demonstration effect at the beginning of the article is as follows. The 0000 file in the picture is a shortcut. The reason for changing this name is to make it always rank first in the file list:

2022_12_12-18_49_46

The script structure shown in this article is applicable to various situations, and any command that can be run in a script can be packaged in this form. When using it yourself, you can also modify the target to an absolute path, so that you only need to copy the shortcut every time.

Title image: Image by pch.vector on Freepik

This article is transferred from: https://sspai.com/post/73026
This site is only for collection, and the copyright belongs to the original author.