.lnk\"); Write-Output $shortcut.TargetPath"`) was unexpected at this time.
FOR /F … IN (``…``) is parsed before%variables% are expanded.
When %shortcutPath% is expanded it contains the text
code
C:\Users\user\Desktop\taskbar\OBS Studio (64bit).lnk
The closing ) that belongs to “(64bit)” appears outside of any
quotes, so CMD thinks it closes the IN( … ) clause and the rest of the
line no longer makes sense – hence the syntax error.
The bullet-proof fix
Do not embed the path inside the PowerShell one-liner.
Pass it as a separate argument – that keeps the parentheses out of the
IN( … ) clause completely and you don’t have to do any escaping.
batch
::: Batch file :::
@echo off
setlocal EnableExtensions EnableDelayedExpansion
rem ---- Configuration ------------------------------------------------
set "shortcutFolder=C:\Users\user\Desktop\taskbar"
set "prefix=_"
set "verbose=1"
rem -------------------------------------------------------------------
for %%F in ("%shortcutFolder%\*.lnk") do (
call :CheckShortcut "%%~F"
)
echo(
echo Finished processing shortcuts.
pause
goto :eof
:CheckShortcut
set "shortcutPath=%~1"
set "targetPath="
rem ---- Get the .lnk target with PowerShell ----------------------
for /f "usebackq delims=" %%T in (`
powershell -NoLogo -NoProfile ^
-Command "(New-Object -ComObject WScript.Shell).CreateShortcut($args[0]).TargetPath" ^
"%shortcutPath%"
`) do set "targetPath=%%T"
rem ----------------------------------------------------------------
if not defined targetPath (
if %verbose%==1 echo WARNING: Could not determine target path for "%shortcutPath%"
goto :eof
)
rem ---- Is the target a folder? ----------------------------------
if exist "!targetPath!\*" (
set "shortcutName=%~n1"
set "newShortcutName=%prefix%%shortcutName%"
set "newShortcutPath=%~dp1!newShortcutName!%~x1"
if /i "!shortcutName!" neq "!newShortcutName!" (
if exist "!newShortcutPath!" (
if %verbose%==1 echo Skipping: "!shortcutName!" already exists with the prefix.
) else (
if %verbose%==1 echo Renaming: "!shortcutName!" → "!newShortcutName!"
ren "%shortcutPath%" "!newShortcutName!%~x1"
)
) else (
if %verbose%==1 echo Skipping: "!shortcutName!" already has the prefix.
)
) else (
if %verbose%==1 echo Skipping: "%shortcutPath%" is not a folder shortcut.
)
goto :eof
What changed?
EnableDelayedExpansion – needed so we can safely use !vars!
inside the parenthesised code block.
PowerShell call powershell … "(New-Object …).CreateShortcut($args[0]).TargetPath" "%shortcutPath%"
The path is %shortcutPath% – given as %1, completely outside the
one-liner, so the troublesome parentheses never reach the IN( … ).
delims= inside the FOR /F so the full returned path (which can
contain spaces) is captured.
With that change your script should run happily, even with shortcuts
whose filenames (or target paths) contain parentheses, spaces, ampersands,
etc.