Create Windows Shortcut Using Python
import subprocess
def run_powershell_command(command):
try:
# Execute PowerShell command
result = subprocess.run(
["powershell", "-Command", command], capture_output=True, text=True
)
# Check if the command executed successfully
if result.returncode == 0:
return True
else:
return False
except Exception as e:
return False
def CreateShortcut(shortcut_name="Shortcut", execution=None, icon=None, save_path=None):
if save_path:
save_path = f"{save_path}\\{shortcut_name}.lnk"
else:
save_path = f"$env:USERPROFILE\\Desktop\\{shortcut_name}.lnk"
output = run_powershell_command(
f"""
$WshShell = New-Object -ComObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut("{save_path}")
$Shortcut.TargetPath = "{execution}"
$Shortcut.IconLocation = "{icon}"
$Shortcut.Save()
"""
)
return output
exePath = "C:\\Windows\\System32\\cmd.exe"
iconPath = "C:\\Users\\avinash\\Downloads\\earth.ico"
IconCreated = CreateShortcut("CMD", exePath, iconPath)
if(IconCreated):
print("Shortcut Created Successfully...")
else:
print("Failed To Create Shortcut...")
Comments
Post a Comment