gpt4 book ai didi

windows - 如果语句嵌套在 for 循环中,则批处理错误 "( unexpected"

转载 作者:可可西里 更新时间:2023-11-01 11:41:50 24 4
gpt4 key购买 nike

每当窗口标题为“广告”时,我编写了这个小脚本来终止 Spotify。现在,它只查找 spotify.exe 进程,如果窗口名称匹配,则将其杀死(下一步是每秒执行一次)。但是,我每次执行它都会出错,告诉我在 IF/i "%A:~0,4"( 中有一个意外的 (,但是这样语句不在我的代码中:Windows 似乎在执行它之前修改了 IF/i "%%A:~0,4%"=="PID:"(

这是脚本:

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION

tasklist /fi "imagename eq spotify.exe" /fo list /v > tmp.txt

FOR /F "usebackq tokens=*" %%A IN ("tmp.txt") DO (
SET test=%%A
echo %%A
IF /i "%%A:~0,4%"=="PID:" (
SET "pid=%%A:PID: =%"
echo %pid%
)
IF /i "%%A:~0,13%"=="Window Title:" (
SET "wintitle=%%A:Window Title: =%"
echo %wintitle%
)
IF "%wintitle%"=="Advertisement" (
taskkill /F /PID %pid%
)
)

PAUSE

错误信息(打开echo):

C:\Users\marco\Desktop>antispotify.bat

C:\Users\marco\Desktop>tasklist /fi "imagename eq spotify.exe" /fo list /v 1>tmp.txt
( was unexpected at this time.
C:\Users\marco\Desktop> IF /i "%A:~0,4" (

有人知道我的代码有什么问题吗?

最佳答案

强制真正终止为广告运行的 Spotify 进程的任务也可以通过使用以下批处理文件而不使用 delayed expansion 来完成。 .

@echo off
setlocal EnableExtensions DisableDelayedExpansion
for /F "tokens=1* delims=:" %%I in ('%SystemRoot%\System32\tasklist.exe /FI "imagename eq spotify.exe" /FO LIST /V 2^>nul') do (
if /I "%%~I" == "PID" (
for /F %%K in ("%%~J") do set "ProcessIdentifier=%%~K"
) else if /I "%%~I" == "Window Title" (
for /F "tokens=*" %%K in ("%%~J") do if /I "%%~K" == "Advertisement" call %SystemRoot%\System32\taskkill.exe /F /PID %%ProcessIdentifier%%
)
)
endlocal

使用延迟环境变量扩展的相同代码:

@echo off
setlocal EnableExtensions EnableDelayedExpansion
for /F "tokens=1* delims=:" %%I in ('%SystemRoot%\System32\tasklist.exe /FI "imagename eq spotify.exe" /FO LIST /V 2^>nul') do (
if /I "%%~I" == "PID" (
for /F %%K in ("%%~J") do set "ProcessIdentifier=%%~K"
) else if /I "%%~I" == "Window Title" (
for /F "tokens=*" %%K in ("%%~J") do if /I "%%~K" == "Advertisement" %SystemRoot%\System32\taskkill.exe /F /PID !ProcessIdentifier!
)
)
endlocal

要了解使用的命令及其工作原理,请打开命令提示符窗口,在其中执行以下命令,并仔细阅读为每个命令显示的所有帮助页面。

  • 调用/?
  • echo/?
  • endlocal/?
  • for/?
  • 如果/?
  • setlocal/?
  • taskkill/?
  • 任务列表/?

另请参阅:How does the Windows Command Interpreter (CMD.EXE) parse scripts?

关于windows - 如果语句嵌套在 for 循环中,则批处理错误 "( unexpected",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57740888/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com