2011-05-30 84 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

相關問題