Bat 文件未在 powershell 中执行

问题描述 投票:0回答:1
cmdkey /list | ForEach-Object{if($_ -like "*target=TERMSRV/*") 
{cmdkey /del:($_ -replace " ","" -replace "Target:","")}}

$Server=Get-Content "C:\Users\ectdcmg3\Documents\servers.txt"

$CMD ="E:\jenkins_slave\jenkins-agent.jnlp.bat"

$User="*"

$Password="*"

foreach ($server in $Server) {

    cmdkey /generic:TERMSRV/$server /user:$User /pass:$Password

    mstsc /v:$server

    invoke-command -computername $server -scriptblock{cmd.exe /c 
    "E:\jenkins_slave\jenkins-agent.jnlp.bat"  2>&1}}

上面是我的代码,每个服务器到达该位置但不执行bat文件。 请帮助修复此代码。

想要在servers.txt文件中指定的每个连接的远程服务器中执行bat文件

powershell file batch-file execution
1个回答
0
投票

尝试运行此脚本并查看它是否正确执行远程服务器上的批处理文件。确保将 * 替换为正确的用户名和密码。

# Clear existing saved credentials for TERMSRV targets
cmdkey /list | ForEach-Object{
    if($_ -like "*target=TERMSRV/*") {
        cmdkey /del:($_ -replace " ","" -replace "Target:","")
    }
}

# Read server names from file
$Servers = Get-Content "C:\Users\ectdcmg3\Documents\servers.txt"

# Specify the path to the batch file
$BatchFilePath = "E:\jenkins_slave\jenkins-agent.jnlp.bat"

# Credentials
$User = "*"  # You need to specify the correct username here
$Password = "*"  # You need to specify the correct password here

foreach ($Server in $Servers) {
    # Save credentials for RDP connection
    cmdkey /generic:TERMSRV/$Server /user:$User /pass:$Password

    # Connect via RDP
    mstsc /v:$Server

    # Execute batch file remotely
    Invoke-Command -ComputerName $Server -Credential (New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, $Password) -ScriptBlock {
        param($BatchFilePath)
        # Change directory to the location where the batch file is located
        Set-Location "E:\jenkins_slave"
        # Execute the batch file
        & $BatchFilePath
    } -ArgumentList $BatchFilePath
}
© www.soinside.com 2019 - 2024. All rights reserved.