需求:生成ANSI格式的.ps1,实现检查开机的时候windows time服务是否启动状态,不是的话启动它。
if((get-service w32time).status -ne 'Running'){start-service w32time -EA 0}
powershell -command xxx
如果 Command 的值为脚本块,则脚本块必须用括号({})括起来
如果是在cmd中,则还需要代码块加双引号,例如"代码块"或者"& ({代码块})"
同样的代码在cmd和powershell中可能有不一样的效果
这句命令在powershell中可以,在cmd中不行
powershell -command ({if((get-service w32time).status -ne 'Running'){start-service w32time -EA 0}})
这句命令在powershell中可以,在cmd中也可以
powershell.exe -Command "if((get-service w32time).status -ne 'Running'){start-service w32time -EA 0}"
这句命令在powershell中可以,在cmd中也可以
powershell -command "& ({if((get-service w32time).status -ne 'Running'){start-service w32time -EA 0}})"
打算创建开机计划任务检查windows time服务是否Running状态,不是的话启动它
cmd.exe /c echo %date% %time%>c:\w32time.ps1
powershell.exe -NoProfile -Command "Add-Content -Path 'C:\w32time.ps1' -Value 'if((get-service w32time).status -ne ''Running''){start-service w32time -EA 0}'"
这样创建的文件是ANSI编码,但是第一行有日期时间,需要注释
#cmd.exe /c echo "#%date% %time%">c:\w32time.ps1
cmd.exe /c echo "#" "%date% %time%">c:\w32time.ps1
#注意>前后没有空格,有空格则达不到(生成的文件是ANSI编码)效果
powershell.exe -NoProfile -Command "Add-Content -Path 'C:\w32time.ps1' -Value 'if((get-service w32time).status -ne ''Running''){start-service w32time -EA 0}'"
#像上面2句创建的文件是ANSI编码,且第一行有日期时间信息
schtasks.exe /create /tn "w32time" /ru SYSTEM /rl highest /sc ONSTART /tr "powershell -ExecutionPolicy Unrestricted -windowstyle hidden -File 'C:\w32time.ps1'" /f
schtasks.exe /run /tn w32time
很多操作文本信息的命令会篡改文件编码,要特别注意,比如cmd.exe /c type nul>c:\w32time.ps1,本来用cmd.exe /c echo %date% %time%>c:\w32time.ps1创建的文件是ANSI编码,第一行有日期时间,需要注释或清空,结果使用cmd.exe /c type nul>c:\w32time.ps1后,ANSI变UTF-8了。于是用cmd.exe /c echo"#""%date% %time%">c:\w32time.ps1来规避,这样生成的文件第一行是#打头的日期时间,后面改内容的话,用Add-Content不会改变文件格式。
if((get-service w32time).status -ne'Running'){start-service w32time -EA 0}代码健壮性再提升下
while(1){
if((get-service w32time).status -ne ''Running''){start-service w32time -EA 0};
if((get-service w32time).status -eq ''Running''){exit};
}
cmd.exe /c echo "#" "%date% %time%">c:\w32time.ps1
powershell.exe -NoProfile -Command "Add-Content -Path 'C:\w32time.ps1' -Value 'while(1){if((get-service w32time).status -ne ''Running''){start-service w32time -EA 0};if((get-service w32time).status -eq ''Running''){exit};}'"
schtasks.exe /create /tn "w32time" /ru SYSTEM /rl highest /sc ONSTART /tr "powershell -ExecutionPolicy Unrestricted -windowstyle hidden -File 'C:\w32time.ps1'" /f
schtasks.exe /run /tn w32time
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。