This article describes how to use PowerShell to create a desktop shortcut for a program or file. In the Windows system, manual operation to create desktop shortcuts is very easy, you only need to right-click the file to the desktop, and then let go, in the pop-up menu to choose "Create a shortcut here" to complete, but to program to achieve this effect is more complicated.
First, we will use the COM component to create a desktop shortcut, the simplest way is to invoke Wscript.Shell this COM component. So how do you create a COM component in PowerShell?
Copy Code code as follows:
$shell = New-object-comobject Wscript.Shell
We created a COM component by New-object This cmdlet, and the component class is wscript.shell to achieve our first step.
The second step, because we want to create shortcuts on the desktop, we also have to find the location of the desktop, that is, the physical path of the desktop. How do we find this, as follows:
Copy Code code as follows:
$desktop = [System.environment]::getfolderpath (' Desktop ']
Used here. NET Framework of the System.Environment class of the GetFolderPath static method, use it can easily get the Windows directory, System32 directory and so on.
The third step is to define the shortcut object and set the related properties.
Copy Code code as follows:
$shortcut = $shell. CreateShortcut ("$desktop \clickme.lnk")
$shortcut. TargetPath = "Calc.exe"
$shortcut. IconLocation = "shell32.dll,23"
It uses the CreateShortcut method of Wscript.Shell This COM object, navigates the shortcut to the desktop, and then defines its target path (Calculator program) for the resulting shortcut object and defines its display icon.
Finally, save the settings.
Copy Code code as follows:
Call the Save method to save the shortcut's settings. So the desktop shortcuts are generated.