在 read-host 執行之前出現 Powershell 腳本憑證提示

在 read-host 執行之前出現 Powershell 腳本憑證提示

我在另一個腳本中呼叫一個腳本:

...
...
powershell C:/temp/script2.ps1"
...
...

下載一些東西後將虛擬機器加入網域。但是,當腳本運行時,「Add-Computer」的提示會在 read-host 之前運行,或者完全跳過:

param (
    [String]$OU,
    [PSCredential]$Credential
    )

$ErrorActionPreference="SilentlyContinue"
Stop-Transcript | out-null
$ErrorActionPreference = "Continue"
Start-Transcript -path C:\script2.txt -append

if ([Environment]::UserInteractive) {
    if (!$OU) { $OU = Read-Host "Enter Tenant Resource Pool Name (exactly as appears in vCenter inventory)" }
    if (!$Credential) { $Credential = Get-Credential -Message "Enter dev domain credentials" }
}

# Add Computer to Dev domain

try {
        Add-Computer -DomainName dev.domain.com -OUPath "OU=$OU,dc=dev,dc=domain,dc=com" -ErrorAction stop -Credential $Credential
        }
catch {
        Write-Warning "Failed to join to domain."
        Read-Host -Prompt "Press Enter to exit"
    Throw $_
        }

這顯然會失敗,因為網域加入需要 -OUPath,而這不會提示。

如果我透過右鍵單擊運行 script2.ps1,它就可以工作。當我像這樣從其他腳本內部運行它時,它失敗了:

wget -O C:/temp/script1.ps1 https://script-source.com:8443/script1.ps1 | powershell C:\temp\script1.ps1

答案1

這似乎可以透過在腳本名稱前面添加一個 & 符號來解決,而不是像我一樣使用 powershell 呼叫它:

powershell_stuff
..
..
& C:/temp/script2.ps1
..
..
morePowershell_stuff

這篇文章的想法:Powershell 腳本執行另一個 powershell 腳本並等待結束

相關內容