【问题标题】:Execute powershell script inside batch file [duplicate]在批处理文件中执行powershell脚本[重复]
【发布时间】:2011-09-05 01:15:25
【问题描述】:

可能重复:
How to execute powershell commands from a batch file?

我想在不创建 ps1 文件的情况下从批处理文件执行以下 powershell 语句

if([System.Diagnostics.EventLog]::SourceExists("dfgdjg") -eq $false){[System.Diagnostics.EventLog]::CreateEventSource("dfgdjg","dfgdjgLogs");}
else{write("Event Log already exists");}

有可能吗?

【问题讨论】:

标签: powershell


【解决方案1】:

一般你可以这样做:

 @powershell -command "yourpowershellcommand"

您可以直接使用powershell.exe,但我建议您使用@powershell的上述形式

【讨论】:

  • 伙计们,它不起作用。我试着做这样的事情 powershell -command 'if([System.Diagnostics.EventLog]::SourceExists("dfgdjg") -eq $false){[System.Diagnostics.EventLog]::CreateEventSource("dfgdjg","dfgdjgLogs ");}else{write("事件日志已经存在");}'
  • @ 只会在echo 开启时导致命令不被回显。在大多数批处理文件中,它无论如何都是关闭的。有或没有@ 的调用在功能上没有区别。
  • 当您将脚本放在文件中时,以下内容可以正常工作:@powershell Invoke-Expression Hello_World.ps1
【解决方案2】:

命令行帮助powershell.exe /? 涵盖以下内容:

-命令 执行指定的命令(和任何参数),就好像它们是 在 Windows PowerShell 命令提示符下键入,然后退出,除非 指定了 NoExit。 Command 的值可以是“-”,一个字符串。或一个 脚本块。 如果 Command 的值为“-”,则从标准读取命令文本 输入。 如果 Command 的值为脚本块,则必须将脚本块括起来 在大括号 ({}) 中。只能在运行 PowerShell.exe 时指定脚本块

最后展示了一个例子:

例子 PowerShell -PSConsoleFile SqlSnapIn.Psc1 PowerShell -version 1.0 -NoLogo -InputFormat text -OutputFormat XML PowerShell -Command {Get-EventLog -LogName security} PowerShell -Command "& {Get-EventLog -LogName security}"

【讨论】:

  • 伙计们,它不起作用。我试着做这样的事情 powershell -command 'if([System.Diagnostics.EventLog]::SourceExists("dfgdjg") -eq $false){[System.Diagnostics.EventLog]::CreateEventSource("dfgdjg","dfgdjgLogs ");‌​}else{write("事件日志已经存在");}'
  • @user:再次阅读帮助条目。然后用&{...} 包围你的命令。然后再试一次。
猜你喜欢
  • 2023-03-30
  • 1970-01-01
  • 2021-03-27
  • 1970-01-01
  • 2023-03-30
  • 1970-01-01
  • 2013-07-30
  • 2012-10-20
  • 2019-08-10
相关资源
最近更新 更多