2011-05-30 123 views
-2

可能重复:
How to execute powershell commands from a batch file?执行PowerShell脚本批处理文件中

我想从一个批处理文件进行创建PS1文件

if([System.Diagnostics.EventLog]::SourceExists("dfgdjg") -eq $false){[System.Diagnostics.EventLog]::CreateEventSource("dfgdjg","dfgdjgLogs");} 
else{write("Event Log already exists");} 
执行下面的PowerShell声明

是否有可能这样做?

+3

请阅读下面的内容:http://tinyurl.com/so-hints – Oded 2011-05-30 20:42:25

回答

1

的命令行帮助powershell.exe /?涵盖这样的:

 
-Command 
    Executes the specified commands (and any parameters) as though they were 
    typed at the Windows PowerShell command prompt, and then exits, unless 
    NoExit is specified. The value of Command can be "-", a string. or a 
    script block. 

    If the value of Command is "-", the command text is read from standard 
    input. 

    If the value of Command is a script block, the script block must be enclosed 

    in braces ({}). You can specify a script block only when running PowerShell.exe 

它显示在最后一个例子:

 
EXAMPLES 
    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}" 
+0

伙计们,它不工作。我尝试做这样的事情powershell命令'if([System.Diagnostics.EventLog] :: SourceExists(“dfgdjg”)-eq $ false){[System.Diagnostics.EventLog] :: CreateEventSource(“dfgdjg”,“dfgdjgLogs “);} else {write(”Event Log already exists“);}' – user602737 2011-05-30 20:53:21

+1

@user:再次阅读帮助条目。然后用'&{...}'环绕你的命令。然后再试一次。 – Joey 2011-05-31 00:06:54

3

一般来说,你可以这样做:

@powershell -command "yourpowershellcommand" 

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

+0

伙计它不工作。我尝试做这样的事情powershell命令'if([System.Diagnostics.EventLog] :: SourceExists(“dfgdjg”)-eq $ false){[System.Diagnostics.EventLog] :: CreateEventSource(“dfgdjg”,“dfgdjgLogs “);} else {write(”Event Log already exists“);}' – user602737 2011-05-30 20:52:27

+1

'@'只会导致该命令在echo'开启时不被回显。无论如何,大多数批处理文件都是关闭的。无论是否使用'@',调用之间没有功能差异。 – Joey 2011-05-31 00:07:47

+0

当您将脚本放在文件中时,以下工作正常: '@powershell Invoke-Expression Hello_World.ps1' – Dominique 2017-05-10 07:33:07