簡體   English   中英

如何在 CMD 中運行 PowerShell

[英]How to run PowerShell in CMD

我正在嘗試在 cmd 命令行中運行 PowerShell 腳本。 有人給了我一個例子,它奏效了:

powershell.exe -noexit "& 'c:\Data\ScheduledScripts\ShutdownVM.ps1'"

但問題是我的 PowerShell 腳本有輸入參數,所以我嘗試了,但它不起作用:

powershell.exe -noexit "& 'D:\Work\SQLExecutor.ps1 -gettedServerName "MY-PC" ' "

錯誤是:

術語 'D:\\Work\\SQLExecutor.ps1 -gettedServerName "MY-PC" ' 未被識別為 cmdlet、函數、

我該如何解決這個問題?

您需要將參數與文件路徑分開:

powershell.exe -noexit "& 'D:\Work\SQLExecutor.ps1 ' -gettedServerName 'MY-PC'"

另一個可以使用 File 參數和位置參數簡化語法的選項:

powershell.exe -noexit -file "D:\Work\SQLExecutor.ps1" "MY-PC"

我想在 Shay Levy 的正確答案中添加以下內容:如果您創建一個小批處理腳本run.cmd來啟動您的 powershell 腳本,您可以讓您的生活更輕松:

運行命令

@echo off & setlocal
set batchPath=%~dp0
powershell.exe -noexit -file "%batchPath%SQLExecutor.ps1" "MY-PC"

將它放在與SQLExecutor.ps1相同的路徑中,從現在開始,您只需雙擊run.cmd即可運行它。


筆記:

  • 如果您需要 run.cmd 批處理中的命令行參數,只需將它們作為%1 ... %9 (或使用%*傳遞所有參數)傳遞給 powershell 腳本,即
    powershell.exe -noexit -file "%batchPath%SQLExecutor.ps1" %*

  • 變量batchPath包含批處理文件本身的執行路徑(這是表達式%~dp0的用途)。 因此,您只需將 powershell 腳本放在與調用批處理文件相同的路徑中。

試試吧:

powershell.exe -noexit D:\Work\SQLExecutor.ps1 -gettedServerName "MY-PC"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM