通过CMD生成脚本

通过CMD生成脚本

我一直在尝试找到这个奇怪问题的答案,但一直没有找到。为了工作,我一直在编写一个小脚本,它可以帮助我的同事和我完成为客户预先配置新笔记本电脑的重复任务。

我知道我要问的可能不是最有效的方法,但无论如何我还是很好奇!

我现在想在我的小脚本中编写临时第二个脚本的行,然后运行它,然后将其删除。但是,我无法让它正常工作。我假设这是由于特殊字符引起的,但我可能错了。

我尝试使用的方法是回声实际命令到文件。最后,我希望它创建一个有效的 .PS1 脚本,执行它,然后删除它。

我想要它写入文件的命令:

$OfficeUninstallStrings = (Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* | Where {$_.DisplayName -like "*Microsoft Office 365*"} | Select UninstallString).UninstallString
ForEach ($UninstallString in $OfficeUninstallStrings) {
    $UninstallEXE = ($UninstallString -split '"')[1]
    $UninstallArg = ($UninstallString -split '"')[2] + " DisplayLevel=False"
    Start-Process -FilePath $UninstallEXE -ArgumentList $UninstallArg -Wait
}    

有人能帮助我弄清楚我忽略了什么吗?

谢谢你!

答案1

这整个概念看起来有点奇怪。为什么不直接使用脚本并运行它呢?.. 好吧.. 随便你.. 你自己做吧。:)

下面的脚本使用随机文件夹名称在文件夹的临时目录中创建文件。

如果要清理它,则需要删除echo命令前面的命令rd /s /q。我不会为你做这个。

您考虑过 powershell 的执行策略吗?

如果需要设置执行策略,请以管理员身份运行批处理,并将 PowerShell 命令(在批处理中)更改为:
PowerShell.exe -ExecutionPolicy Bypass -File "%wholePS1Path%"

如果这不管用,这里有一些其他方法

  @echo off
  setlocal

  set outputFile=uninstall_office.PS1
  set outputFilePath=%TEMP%\%RANDOM%
  set wholePS1Path="%outputFilePath%\%outputFile%"

  echo $OfficeUninstallStrings = (Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* ^| Where {$_.DisplayName -like "*Microsoft Office 365*"} ^| Select UninstallString).UninstallString >%outputFile%
  echo ForEach ($UninstallString in $OfficeUninstallStrings) { >>%outputFile%
  echo     $UninstallEXE = ($UninstallString -split ^'^"^')[1] >>%outputFile%
  echo     $UninstallArg = ($UninstallString -split ^'^"^')[2] + " DisplayLevel=False" >>%outputFile%
  echo     Start-Process -FilePath $UninstallEXE -ArgumentList $UninstallArg -Wait >>%outputFile%
  echo } >>%outputFile%

  :: Run the powershell command
  powershell -File "%wholePS1Path%"
  set powershell_error=%ERRORLEVEL%

  :: Remove this line to clean up once you are SURE it is working.
  :: Of course, rd can be brutal.
  echo rd /s /q "%outputFilePath%"

  endlocal && exit /b %powershell_error%

相关内容