RUN Bat files with AutoIt Number - batch-file

I would like to run AutoIt application, change the number in the edit box AND BASED on this number the BAT file will run.
As example, I would like to change date for today one or any other. Based and when I will run BAT file from AutoIt app, BAT file will use this date.
Is it actually possible???
This is bat file variables:
set newDay=22
set newMonth=11
set newYear=2016
And this is AutoIt part:
While 1
$msg = GUIGetMsg()
Select
Case $msg = $GUI_EVENT_CLOSE
ExitLoop
Case $msg = $xxx
Run("n:\xxx\xxx\xxx.bat")
EndSelect
WEnd

To pass from the autoit code:
While 1
$msg = GUIGetMsg()
Select
Case $msg = $GUI_EVENT_CLOSE
ExitLoop
Case $msg = $xxx
Run("n:\xxx\xxx\xxx.bat" & " " & $newDay & " " & $newMonth & " " & $newYear)
EndSelect
WEnd
And to be received by the batch file:
set newDay=%1
set newMonth=%2
set newYear=%3

Related

Getting a Windows command prompt contents to a text file

I want to write a batch utility to copy the output of a command prompt window to a file. I run my command prompt windows with the maximum depth of 9999 lines, and occasionally I want to grab the output of a command whose output is off-screen. I can do this manually with the keys Ctrl-A, Ctrl-Cand then pasting the result into Notepad - I just want to automate it in a batch file with a call to:
SaveScreen <text file name>
I know I can do it with redirection, but that would involve knowing that I will need to save the output of a batch command sequence beforehand.
So if I had a batch script:
call BuildPhase1.bat
if "%ErrorLevel% gtr 0 goto :ErrorExit
call BuildPhase2.bat
if "%ErrorLevel% gtr 0 goto :ErrorExit
call BuildPhase3.bat
if "%ErrorLevel% gtr 0 goto :ErrorExit
I could write:
cls
call BuildPhase1.bat
if "%ErrorLevel% gtr 0 call SaveScreen.bat BuildPhase1.err & goto :ErrorExit
call BuildPhase2.bat
if "%ErrorLevel% gtr 0 call SaveScreen.bat BuildPhase2.err & goto :ErrorExit
call BuildPhase3.bat
if "%ErrorLevel% gtr 0 call SaveScreen.bat BuildPhase3.err & goto :ErrorExit
or I could just type SaveScreen batch.log when I see that a run has failed.
My experiments have got me this far:
<!-- : Begin batch script
#cscript //nologo "%~f0?.wsf" //job:JS
#exit /b
----- Begin wsf script --->
<package>
<job id="JS">
<script language="JScript">
var oShell = WScript.CreateObject("WScript.Shell");
oShell.SendKeys ("hi folks{Enter}") ;
oShell.SendKeys ("^A") ; // Ctrl-A (select all)
oShell.SendKeys ("^C") ; // Ctrl-C (copy)
oShell.SendKeys ("% ES") ; // Alt-space, E, S (select all via menu)
oShell.SendKeys ("% EY") ; // Alt-space, E, Y (copy via menu)
// ... invoke a notepad session, paste the clipboard into it, save to a file
WScript.Quit () ;
</script>
</job>
</package>
My keystrokes are making it to the command prompt so presumably I have the correct window focused - it just seems to be ignoring the Ctrl and Alt modifiers. It also recognises Ctrl-C but not Ctrl-A. Because it has ignored the Ctrl-A to select all the text, the Ctrl-C causes the batch file to think it has seen a break command.
I've seen the other answers like this one but they all deal with methods using redirection, rather than a way of doing it after the fact "on demand".
* UPDATE *
On the basis of #dxiv's pointer, here is a batch wrapper for the routine:
Get-ConsoleAsText.bat
:: save the contents of the screen console buffer to a disk file.
#set "_Filename=%~1"
#if "%_Filename%" equ "" #set "_Filename=Console.txt"
#powershell Get-ConsoleAsText.ps1 >"%_Filename%"
#exit /b 0
The Powershell routine is pretty much as was presented in the link, except that:
I had to sanitise it to remove some of the more interesting character substitutions the select/copy/paste operation introduced.
The original saved the trailing spaces as well. Those are now trimmed.
Get-ConsoleAsText.ps1
# Get-ConsoleAsText.ps1 (based on: https://devblogs.microsoft.com/powershell/capture-console-screen/)
#
# The script captures console screen buffer up to the current cursor position and returns it in plain text format.
#
# Returns: ASCII-encoded string.
#
# Example:
#
# $textFileName = "$env:temp\ConsoleBuffer.txt"
# .\Get-ConsoleAsText | out-file $textFileName -encoding ascii
# $null = [System.Diagnostics.Process]::Start("$textFileName")
#
if ($host.Name -ne 'ConsoleHost') # Check the host name and exit if the host is not the Windows PowerShell console host.
{
write-host -ForegroundColor Red "This script runs only in the console host. You cannot run this script in $($host.Name)."
exit -1
}
$textBuilder = new-object system.text.stringbuilder # Initialize string builder.
$bufferWidth = $host.ui.rawui.BufferSize.Width # Grab the console screen buffer contents using the Host console API.
$bufferHeight = $host.ui.rawui.CursorPosition.Y
$rec = new-object System.Management.Automation.Host.Rectangle 0,0,($bufferWidth - 1),$bufferHeight
$buffer = $host.ui.rawui.GetBufferContents($rec)
for($i = 0; $i -lt $bufferHeight; $i++) # Iterate through the lines in the console buffer.
{
$Line = ""
for($j = 0; $j -lt $bufferWidth; $j++)
{
$cell = $buffer[$i,$j]
$line = $line + $cell.Character
}
$line = $line.trimend(" ") # remove trailing spaces.
$null = $textBuilder.Append($line)
$null = $textBuilder.Append("`r`n")
}
return $textBuilder.ToString()
The contents of the console buffer can be retrieved with the PS script from PowerShell's team blog Capture console screen mentioned in a comment, now edited into OP's question.
The last line could also be changed to copy the contents to the clipboard instead of returning it.
Set-Clipboard -Value $textBuilder.ToString()
As a side note, the reasons for using a StringBuilder rather than direct concatenation are discussed in How does StringBuilder work internally in C# and How the StringBuilder class is implemented.

Looking for MORE/MOVE solutions that can handle files with more than 65534 rows

I have numerous uniquely named .CSV files that I need to remove the first 17 lines from. Some of these files exceed 65534 rows so my MORE/MOVE Batch script is not working. Looking for alternative solutions.
#echo off
for %%a in (*.csv) do (
more +17 "%%a" >"%%a.new"
move /y "%%a.new" "%%a" >nul
)
Regardless of number of rows input I am looking to have the 17 header rows removed and new file with all remaining rows built.
Here's a powershell option; this one uses a stream to cater for your large files:
$csvs = Get-ChildItem -Path "P:\ath to\your csvs" -Filter *.csv
foreach ( $csv in $csvs ) {
$fin = New-Object System.IO.StreamReader( $csv.FullName )
$fout = New-Object System.IO.StreamWriter( $csv.FullName+".new" )
try {
for( $s = 1; $s -le 17 -and !$fin.EndOfStream; $s++ ) {
$fin.ReadLine()
}
while( !$fin.EndOfStream ) {
$fout.WriteLine( $fin.ReadLine() )
}
}
finally {
$fout.Close()
$fin.Close()
}
}
Just change the path to your .csvs on the first line, before testing it.
I have purposely left out the deletion of the original files, simply appending .new to the new filenames to allow you time to check the results, test the speed etc. I will leave it to you to include a Rename/Delete or Move should you feel the need to extend the functionality.
Here's a one-line solution
for %%a in (*.txt) do powershell -Com "sc -Path '%%a' -Value (gc '%%a' | select -Skip 17)"
where gc and sc are default aliases for Get-Content and Set-Content respectively. See also
Powershell select-object skip multiple lines?
Powershell skip first 2 lines of txt file when importing it
If your files are huge then it'll be better to read in lines or blocks which can also be implemented easily using file functions, [IO.File]::OpenText or the -ReadCount option of Get-Content in PowerShell
Reading large text files with Powershell
Reading very BIG text files using PowerShell
How to process a file in PowerShell line-by-line as a stream
How can I make this PowerShell script parse large files faster?
As Squashman mentioned, for /f also has an option to skip lines at the beginning of the file
for %%a in (*.csv) do (
for /f "usebackq skip=17 delims=" %%l in ("%%f") do #echo(%%l>>"%%a.new"
move /y "%%a.new" "%%a" >nul
)
But that won't work if your file contains lines with special characters like & or |. For more information about it run for /?
Make your own cut command. This is VBScript ported to VB.NET.
Cut
cut {t|b} {i|x} NumOfLines
Cuts the number of lines from the top or bottom of file.
t - top of the file
b - bottom of the file
i - include n lines
x - exclude n lines
Example
cut t i 5 < "%systemroot%\win.ini"
Cut.bat
REM Cut.bat
REM This file compiles Cut.vb to Cut.exe
REM Cut.exe Removes specified from top or bottom of lines from StdIn and writes to StdOut
REM To use
REM cut {t|b} {i|x} NumOfLines
Rem Cuts the number of lines from the top or bottom of file.
Rem t - top of the file
Rem b - bottom of the file
Rem i - include n lines
Rem x - exclude n lines
Rem
Rem Example - Includes first 5 lines Win.ini
Rem
Rem cut t i 5 < "%systemroot%\win.ini"
"C:\Windows\Microsoft.NET\Framework\v4.0.30319\vbc.exe" /target:exe /out:"%~dp0\Cut.exe" "%~dp0\Cut.vb" /verbose
pause
Cut.vb
'DeDup.vb
Imports System
Imports System.IO
Imports System.Runtime.InteropServices
Imports Microsoft.Win32
Public Module DeDup
Sub Main
Dim Arg() As Object
Dim RS as Object
Dim LineCount as Object
Dim Line as Object
Arg = Split(Command(), " ")
rs = CreateObject("ADODB.Recordset")
With rs
.Fields.Append("LineNumber", 4)
.Fields.Append("Txt", 201, 5000)
.Open
LineCount = 0
Line=Console.readline
Do Until Line = Nothing
LineCount = LineCount + 1
.AddNew
.Fields("LineNumber").value = LineCount
.Fields("Txt").value = Console.readline
.UpDate
Line = Console.ReadLine
Loop
.Sort = "LineNumber ASC"
If LCase(Arg(0)) = "t" then
If LCase(Arg(1)) = "i" then
.filter = "LineNumber < " & LCase(Arg(2)) + 1
ElseIf LCase(Arg(1)) = "x" then
.filter = "LineNumber > " & LCase(Arg(2))
End If
ElseIf LCase(Arg(0)) = "b" then
If LCase(Arg(1)) = "i" then
.filter = "LineNumber > " & LineCount - LCase(Arg(2))
ElseIf LCase(Arg(1)) = "x" then
.filter = "LineNumber < " & LineCount - LCase(Arg(2)) + 1
End If
End If
Do While not .EOF
Console.writeline(.Fields("Txt").Value)
.MoveNext
Loop
End With
End Sub
End Module

How to have a Batch File create a shortcut on desktop [duplicate]

how to create a shortcut for a exe from a batch file.
i tried
call link.bat "c:\program Files\App1\program1.exe" "C:\Documents and Settings\%USERNAME%\Desktop" "C:\Documents and Settings\%USERNAME%\Start Menu\Programs" "Program1 shortcut"
but it did not worked.
link.bat can be found at
http://www.robvanderwoude.com/amb_shortcuts.html
Your link points to a Windows 95/98 version and I guess you have at least Windows 2000 or XP. You should try the NT version here.
Alternatively use a little VBScript that you can call from the command line:
set objWSHShell = CreateObject("WScript.Shell")
set objFso = CreateObject("Scripting.FileSystemObject")
' command line arguments
' TODO: error checking
sShortcut = objWSHShell.ExpandEnvironmentStrings(WScript.Arguments.Item(0))
sTargetPath = objWSHShell.ExpandEnvironmentStrings(WScript.Arguments.Item(1))
sWorkingDirectory = objFso.GetAbsolutePathName(sShortcut)
set objSC = objWSHShell.CreateShortcut(sShortcut)
objSC.TargetPath = sTargetPath
objSC.WorkingDirectory = sWorkingDirectory
objSC.Save
Save the file as createLink.vbs and call it like this to get what you originally tried:
cscript createLink.vbs "C:\Documents and Settings\%USERNAME%\Desktop\Program1 shortcut.lnk" "c:\program Files\App1\program1.exe"
cscript createLink.vbs "C:\Documents and Settings\%USERNAME%\Start Menu\Programs\Program1 shortcut.lnk" "c:\program Files\App1\program1.exe"
That said I urge you not to use hardcoded paths like "Start Menu" since they're different in localized versions of windows. Modify the script instead to use special folders.
This is the kind of thing that PowerShell is really good at, and is therefore a reason to eschew batch files and get on PowerShell the bandwagon.
PowerShell can talk to .NET. For example, you can get the location of the Desktop like this:
[Environment]::GetFolderPath("Desktop")
PowerShell can talk to COM objects, including WScript.Shell, which can create shortcuts:
New-Object -ComObject WScript.Shell).CreateShortcut( ... )
So your script might look like:
$linkPath = Join-Path ([Environment]::GetFolderPath("Desktop")) "MyShortcut.lnk"
$targetPath = Join-Path ([Environment]::GetFolderPath("ProgramFiles")) "MyCompany\MyProgram.exe"
$link = (New-Object -ComObject WScript.Shell).CreateShortcut( $linkpath )
$link.TargetPath = $targetPath
$link.Save()
Shortcuts have a lot of settings that WScript.Shell can't manipulate, like the "run as administrator" option. These are only accessible through the Win32 interface IShellLinkDataList, which is a real pain to use, but it can be done.
Using vbscript:
set WshShell = WScript.CreateObject("WScript.Shell" )
strDesktop = WshShell.SpecialFolders("AllUsersDesktop" )
set oShellLink = WshShell.CreateShortcut(strDesktop & "\shortcut name.lnk" )
oShellLink.TargetPath = "c:\application folder\application.exe"
oShellLink.WindowStyle = 1
oShellLink.IconLocation = "c:\application folder\application.ico"
oShellLink.Description = "Shortcut Script"
oShellLink.WorkingDirectory = "c:\application folder"
oShellLink.Save
Ref: http://www.tomshardware.com/forum/52871-45-creating-desktop-shortcuts-command-line
Failing that, a quick google search shows there's a number of third party tools that can create .lnk files for application shortcuts. I'm assuming you need to stick to stuff that's available natively on Windows though? VBscript is probably your best bet, otherwise I'd suggest trying copying the .lnk file from your machine or using it as a sample to see the correct format for a shortcut file.
On XP I wrote makeshortcut.vbs
Set oWS = WScript.CreateObject("WScript.Shell")
If wscript.arguments.count < 4 then
WScript.Echo "usage: makeshortcut.vbs shortcutPath targetPath arguments workingDir "
WScript.Quit
end If
shortcutPath = wscript.arguments(0) & ".LNK"
targetPath = wscript.arguments(1)
arguments = wscript.arguments(2)
workingDir = wscript.arguments(3)
WScript.Echo "Creating shortcut " & shortcutPath & " targetPath=" & targetPath & " arguments=" & arguments & " workingDir=" & workingDir
Set oLink = oWS.CreateShortcut(shortcutPath)
oLink.TargetPath = targetPath
oLink.Arguments = arguments
' oLink.Description = "MyProgram"
' oLink.HotKey = "ALT+CTRL+F"
' oLink.IconLocation = "C:\Program Files\MyApp\MyProgram.EXE, 2"
' oLink.WindowStyle = "1"
oLink.WorkingDirectory = workingDir
oLink.Save
It takes exactly 4 args, so it could be improved by making the later 2 optional.I only post because it echo's usage, which might be useful to some. I like WS's soln using special folders and ExpandEnvironmentStrings
Additional note: the link.bat you're using is for Windows 95/98 only:
This batch file is for Windows 95/98 only. I will post the NT equivalent in
the NT newsgroup soon.
NT version is posted at http://www.robvanderwoude.com/amb_shortcutsnt.html instead. You might try that for a .bat approach if preferred over vbscript.
Alternative method, using a third party utility:
Creating a Shortcut from the command line (batch file)
XXMKLINK:
With XXMKLINK, you can write a batch file for software
installation which has been done by specialized installation
programs. Basically, XXMKLINK is a tool that gathers various
information from a command line and packages it into a shortcut.
xxmklink spath opath
where
spath path of the shortcut (.lnk added as needed)
opath path of the object represented by the shortcut
You can check shortcutjs.bat:
::creates a shortcut that will start the target with minimized window and admin permissions
shortcutjs.bat -linkfile myscriptMin.lnk -target "%cd%\myscript.bat" -windowstyle 7 -adminpermissions yes
::creates a shortcut with a hot keys
shortcutjs.bat -linkfile myscriptHK.lnk -target "%cd%\myscript.bat" -hotkey "ALT+CTRL+P"
With this you can also edit existing shortcut or only display its properties.
This worked for me on Windows XP ms-dos, I still haven't tried it on Windows 7. It's just like creating a symbolic link in Linux.
shortcut -T source.exe destination.lnk
In the end I decided to write the correct script, because no solution works for me
You will need two fileLocal Settings\
first
createSCUT.bat
#echo on
set VBS=createSCUT.vbs
set SRC_LNK="shortcut1.lnk"
set ARG1_APPLCT="C:\Program Files\Google\Chrome\Application\chrome.exe"
set ARG2_APPARG="--profile-directory=QuteQProfile 25QuteQ"
set ARG3_WRKDRC="C:\Program Files\Google\Chrome\Application"
set ARG4_ICOLCT="%USERPROFILE%\Local Settings\Application Data\Google\Chrome\User Data\Profile 25\Google Profile.ico"
cscript %VBS% %SRC_LNK% %ARG1_APPLCT% %ARG2_APPARG% %ARG3_WRKDRC% %ARG4_ICOLCT%
and second
createSCUT.vbs
Set objWSHShell = WScript.CreateObject("WScript.Shell")
set objWSHShell = CreateObject("WScript.Shell")
set objFso = CreateObject("Scripting.FileSystemObject")
If WScript.arguments.count = 5 then
WScript.Echo "usage: makeshortcut.vbs shortcutPath targetPath arguments workingDir IconLocation"
sShortcut = objWSHShell.ExpandEnvironmentStrings(WScript.Arguments.Item(0))
set objSC = objWSHShell.CreateShortcut(sShortcut)
sTargetPath = objWSHShell.ExpandEnvironmentStrings(WScript.Arguments.Item(1))
sArguments = objWSHShell.ExpandEnvironmentStrings(WScript.Arguments.Item(2))
sWorkingDirectory = objWSHShell.ExpandEnvironmentStrings(WScript.Arguments.Item(3))
sIconLocation = objWSHShell.ExpandEnvironmentStrings(WScript.Arguments.Item(4))
objSC.TargetPath = sTargetPath
rem http://www.bigresource.com/VB-simple-replace-function-5bAN30qRDU.html#
objSC.Arguments = Replace(sArguments, "QuteQ", Chr(34))
rem http://msdn.microsoft.com/en-us/library/f63200h0(v=vs.90).aspx http://msdn.microsoft.com/en-us/library/267k4fw5(v=vs.90).aspx
objSC.WorkingDirectory = sWorkingDirectory
objSC.Description = "Love Peace Bliss"
rem 1 restore 3 max 7 min
objSC.WindowStyle = "3"
rem objSC.Hotkey = "Ctrl+Alt+e";
objSC.IconLocation = sIconLocation
objSC.Save
WScript.Quit
end If
If WScript.arguments.count = 4 then
WScript.Echo "usage: makeshortcut.vbs shortcutPath targetPath arguments workingDir "
sShortcut = objWSHShell.ExpandEnvironmentStrings(WScript.Arguments.Item(0))
set objSC = objWSHShell.CreateShortcut(sShortcut)
sTargetPath = objWSHShell.ExpandEnvironmentStrings(WScript.Arguments.Item(1))
sArguments = objWSHShell.ExpandEnvironmentStrings(WScript.Arguments.Item(2))
sWorkingDirectory = objWSHShell.ExpandEnvironmentStrings(WScript.Arguments.Item(3))
objSC.TargetPath = sTargetPath
objSC.Arguments = Replace(sArguments, "QuteQ", Chr(34))
objSC.WorkingDirectory = sWorkingDirectory
objSC.Description = "Love Peace Bliss"
objSC.WindowStyle = "3"
objSC.Save
WScript.Quit
end If
If WScript.arguments.count = 2 then
WScript.Echo "usage: makeshortcut.vbs shortcutPath targetPath"
sShortcut = objWSHShell.ExpandEnvironmentStrings(WScript.Arguments.Item(0))
set objSC = objWSHShell.CreateShortcut(sShortcut)
sTargetPath = objWSHShell.ExpandEnvironmentStrings(WScript.Arguments.Item(1))
sWorkingDirectory = objFso.GetAbsolutePathName(sShortcut)
objSC.TargetPath = sTargetPath
objSC.WorkingDirectory = sWorkingDirectory
objSC.Save
WScript.Quit
end If

Accept parameters from a .Net console app into a Batch file

I am trying to pass parameters from a .Net console app to a batch file. The parameters are not coming into the batch file.
How can I properly set up passing the parameters into the bat file?
Here is the method in the console app that I'm executing.
private static int ProcessBatFile(string ifldr, string ofldr, string iext, string oext, Int16 filewidth, Int16 fileheight, Int16 ctr)
{
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = ConfigurationSettings.AppSettings.Get("BatProcessDir") + "imagemagick.bat";
psi.Arguments = "-ifldr=" + ifldr + " -ofldr=" + ofldr + " -iext=" + iext + " -oext=" + oext + " -iwid=" + filewidth + " -ihgt=" + fileheight;
psi.UseShellExecute = false;
Process process = new Process();
process.StartInfo = psi;
process.Start();
return ctr;
}
Below, is the code in the bat file I'm trying to execute:
#echo on
echo %ofldr%
echo %ifldr%
echo %iwid%
echo %ihgt%
echo %oext%
echo %iext%
If you pass them as paramters, you can do this in the c# code:
psi.Arguments = ifldr + " " + ofldr + " " + iext + " " + oext + " " + filewidth + " " + fileheight;
and do this in the batch file:
#echo on
set ifldr=%1
set ofldr=%2
set iext=%3
set oext=%4
set iwid=%5
set ihgt=%6
echo %ofldr%
echo %ifldr%
echo %iwid%
echo %ihgt%
echo %oext%
echo %iext%
As an alternative solution, you can also directly modify the environment before executing the batch file using System.Environment.SetEnvironmentVariable:
System.Environment.SetEnvironmentVariable ("ifldr", ifldr);
....
This causes less problems if the parameters may contain spaces.

creating a shortcut for a exe from a batch file

how to create a shortcut for a exe from a batch file.
i tried
call link.bat "c:\program Files\App1\program1.exe" "C:\Documents and Settings\%USERNAME%\Desktop" "C:\Documents and Settings\%USERNAME%\Start Menu\Programs" "Program1 shortcut"
but it did not worked.
link.bat can be found at
http://www.robvanderwoude.com/amb_shortcuts.html
Your link points to a Windows 95/98 version and I guess you have at least Windows 2000 or XP. You should try the NT version here.
Alternatively use a little VBScript that you can call from the command line:
set objWSHShell = CreateObject("WScript.Shell")
set objFso = CreateObject("Scripting.FileSystemObject")
' command line arguments
' TODO: error checking
sShortcut = objWSHShell.ExpandEnvironmentStrings(WScript.Arguments.Item(0))
sTargetPath = objWSHShell.ExpandEnvironmentStrings(WScript.Arguments.Item(1))
sWorkingDirectory = objFso.GetAbsolutePathName(sShortcut)
set objSC = objWSHShell.CreateShortcut(sShortcut)
objSC.TargetPath = sTargetPath
objSC.WorkingDirectory = sWorkingDirectory
objSC.Save
Save the file as createLink.vbs and call it like this to get what you originally tried:
cscript createLink.vbs "C:\Documents and Settings\%USERNAME%\Desktop\Program1 shortcut.lnk" "c:\program Files\App1\program1.exe"
cscript createLink.vbs "C:\Documents and Settings\%USERNAME%\Start Menu\Programs\Program1 shortcut.lnk" "c:\program Files\App1\program1.exe"
That said I urge you not to use hardcoded paths like "Start Menu" since they're different in localized versions of windows. Modify the script instead to use special folders.
This is the kind of thing that PowerShell is really good at, and is therefore a reason to eschew batch files and get on PowerShell the bandwagon.
PowerShell can talk to .NET. For example, you can get the location of the Desktop like this:
[Environment]::GetFolderPath("Desktop")
PowerShell can talk to COM objects, including WScript.Shell, which can create shortcuts:
New-Object -ComObject WScript.Shell).CreateShortcut( ... )
So your script might look like:
$linkPath = Join-Path ([Environment]::GetFolderPath("Desktop")) "MyShortcut.lnk"
$targetPath = Join-Path ([Environment]::GetFolderPath("ProgramFiles")) "MyCompany\MyProgram.exe"
$link = (New-Object -ComObject WScript.Shell).CreateShortcut( $linkpath )
$link.TargetPath = $targetPath
$link.Save()
Shortcuts have a lot of settings that WScript.Shell can't manipulate, like the "run as administrator" option. These are only accessible through the Win32 interface IShellLinkDataList, which is a real pain to use, but it can be done.
Using vbscript:
set WshShell = WScript.CreateObject("WScript.Shell" )
strDesktop = WshShell.SpecialFolders("AllUsersDesktop" )
set oShellLink = WshShell.CreateShortcut(strDesktop & "\shortcut name.lnk" )
oShellLink.TargetPath = "c:\application folder\application.exe"
oShellLink.WindowStyle = 1
oShellLink.IconLocation = "c:\application folder\application.ico"
oShellLink.Description = "Shortcut Script"
oShellLink.WorkingDirectory = "c:\application folder"
oShellLink.Save
Ref: http://www.tomshardware.com/forum/52871-45-creating-desktop-shortcuts-command-line
Failing that, a quick google search shows there's a number of third party tools that can create .lnk files for application shortcuts. I'm assuming you need to stick to stuff that's available natively on Windows though? VBscript is probably your best bet, otherwise I'd suggest trying copying the .lnk file from your machine or using it as a sample to see the correct format for a shortcut file.
On XP I wrote makeshortcut.vbs
Set oWS = WScript.CreateObject("WScript.Shell")
If wscript.arguments.count < 4 then
WScript.Echo "usage: makeshortcut.vbs shortcutPath targetPath arguments workingDir "
WScript.Quit
end If
shortcutPath = wscript.arguments(0) & ".LNK"
targetPath = wscript.arguments(1)
arguments = wscript.arguments(2)
workingDir = wscript.arguments(3)
WScript.Echo "Creating shortcut " & shortcutPath & " targetPath=" & targetPath & " arguments=" & arguments & " workingDir=" & workingDir
Set oLink = oWS.CreateShortcut(shortcutPath)
oLink.TargetPath = targetPath
oLink.Arguments = arguments
' oLink.Description = "MyProgram"
' oLink.HotKey = "ALT+CTRL+F"
' oLink.IconLocation = "C:\Program Files\MyApp\MyProgram.EXE, 2"
' oLink.WindowStyle = "1"
oLink.WorkingDirectory = workingDir
oLink.Save
It takes exactly 4 args, so it could be improved by making the later 2 optional.I only post because it echo's usage, which might be useful to some. I like WS's soln using special folders and ExpandEnvironmentStrings
Additional note: the link.bat you're using is for Windows 95/98 only:
This batch file is for Windows 95/98 only. I will post the NT equivalent in
the NT newsgroup soon.
NT version is posted at http://www.robvanderwoude.com/amb_shortcutsnt.html instead. You might try that for a .bat approach if preferred over vbscript.
Alternative method, using a third party utility:
Creating a Shortcut from the command line (batch file)
XXMKLINK:
With XXMKLINK, you can write a batch file for software
installation which has been done by specialized installation
programs. Basically, XXMKLINK is a tool that gathers various
information from a command line and packages it into a shortcut.
xxmklink spath opath
where
spath path of the shortcut (.lnk added as needed)
opath path of the object represented by the shortcut
You can check shortcutjs.bat:
::creates a shortcut that will start the target with minimized window and admin permissions
shortcutjs.bat -linkfile myscriptMin.lnk -target "%cd%\myscript.bat" -windowstyle 7 -adminpermissions yes
::creates a shortcut with a hot keys
shortcutjs.bat -linkfile myscriptHK.lnk -target "%cd%\myscript.bat" -hotkey "ALT+CTRL+P"
With this you can also edit existing shortcut or only display its properties.
This worked for me on Windows XP ms-dos, I still haven't tried it on Windows 7. It's just like creating a symbolic link in Linux.
shortcut -T source.exe destination.lnk
In the end I decided to write the correct script, because no solution works for me
You will need two fileLocal Settings\
first
createSCUT.bat
#echo on
set VBS=createSCUT.vbs
set SRC_LNK="shortcut1.lnk"
set ARG1_APPLCT="C:\Program Files\Google\Chrome\Application\chrome.exe"
set ARG2_APPARG="--profile-directory=QuteQProfile 25QuteQ"
set ARG3_WRKDRC="C:\Program Files\Google\Chrome\Application"
set ARG4_ICOLCT="%USERPROFILE%\Local Settings\Application Data\Google\Chrome\User Data\Profile 25\Google Profile.ico"
cscript %VBS% %SRC_LNK% %ARG1_APPLCT% %ARG2_APPARG% %ARG3_WRKDRC% %ARG4_ICOLCT%
and second
createSCUT.vbs
Set objWSHShell = WScript.CreateObject("WScript.Shell")
set objWSHShell = CreateObject("WScript.Shell")
set objFso = CreateObject("Scripting.FileSystemObject")
If WScript.arguments.count = 5 then
WScript.Echo "usage: makeshortcut.vbs shortcutPath targetPath arguments workingDir IconLocation"
sShortcut = objWSHShell.ExpandEnvironmentStrings(WScript.Arguments.Item(0))
set objSC = objWSHShell.CreateShortcut(sShortcut)
sTargetPath = objWSHShell.ExpandEnvironmentStrings(WScript.Arguments.Item(1))
sArguments = objWSHShell.ExpandEnvironmentStrings(WScript.Arguments.Item(2))
sWorkingDirectory = objWSHShell.ExpandEnvironmentStrings(WScript.Arguments.Item(3))
sIconLocation = objWSHShell.ExpandEnvironmentStrings(WScript.Arguments.Item(4))
objSC.TargetPath = sTargetPath
rem http://www.bigresource.com/VB-simple-replace-function-5bAN30qRDU.html#
objSC.Arguments = Replace(sArguments, "QuteQ", Chr(34))
rem http://msdn.microsoft.com/en-us/library/f63200h0(v=vs.90).aspx http://msdn.microsoft.com/en-us/library/267k4fw5(v=vs.90).aspx
objSC.WorkingDirectory = sWorkingDirectory
objSC.Description = "Love Peace Bliss"
rem 1 restore 3 max 7 min
objSC.WindowStyle = "3"
rem objSC.Hotkey = "Ctrl+Alt+e";
objSC.IconLocation = sIconLocation
objSC.Save
WScript.Quit
end If
If WScript.arguments.count = 4 then
WScript.Echo "usage: makeshortcut.vbs shortcutPath targetPath arguments workingDir "
sShortcut = objWSHShell.ExpandEnvironmentStrings(WScript.Arguments.Item(0))
set objSC = objWSHShell.CreateShortcut(sShortcut)
sTargetPath = objWSHShell.ExpandEnvironmentStrings(WScript.Arguments.Item(1))
sArguments = objWSHShell.ExpandEnvironmentStrings(WScript.Arguments.Item(2))
sWorkingDirectory = objWSHShell.ExpandEnvironmentStrings(WScript.Arguments.Item(3))
objSC.TargetPath = sTargetPath
objSC.Arguments = Replace(sArguments, "QuteQ", Chr(34))
objSC.WorkingDirectory = sWorkingDirectory
objSC.Description = "Love Peace Bliss"
objSC.WindowStyle = "3"
objSC.Save
WScript.Quit
end If
If WScript.arguments.count = 2 then
WScript.Echo "usage: makeshortcut.vbs shortcutPath targetPath"
sShortcut = objWSHShell.ExpandEnvironmentStrings(WScript.Arguments.Item(0))
set objSC = objWSHShell.CreateShortcut(sShortcut)
sTargetPath = objWSHShell.ExpandEnvironmentStrings(WScript.Arguments.Item(1))
sWorkingDirectory = objFso.GetAbsolutePathName(sShortcut)
objSC.TargetPath = sTargetPath
objSC.WorkingDirectory = sWorkingDirectory
objSC.Save
WScript.Quit
end If

Resources