【问题标题】:How to trigger a bat file on remote server only after the pssession is formed on the server仅在服务器上形成 pssession 后如何在远程服务器上触发 bat 文件
【发布时间】:2020-09-15 00:45:09
【问题描述】:
Write-Host "Welcome to Application Process Start/Stop Dashboard" -ForegroundColor Green
Write-Host "`n" "1) Stop" "`n" "2) Start"
[int]$resp = Read-Host "Choose option 1 or 2 for stopping or starting application process respectively"
if($resp -eq 1)
{
[System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
$result = [System.Windows.Forms.MessageBox]::Show('Are you sure you want to STOP ?', "Info" , 4 )
if ($result -eq 'Yes') 
{
$user = "NAmarshmellow"
$server = "Desktop_10U"
$storesess = New-PSSession -ComputerName $server -Credential $user 
Enter-PSSession -Session $storesess
$path = "\\Users\mellow\Documents\Proj"
$pwd = Read-Host -AsSecureString
$bstr = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($pwd)
$value = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($bstr)
NET USE $path /user:$user $value
Start-Process cmd -ArgumentList "/C C:\Users\Desktop_10U\Documents\Some\Stop.bat" -Wait
Clear-Variable storesess
Exit-PSSession
}
}

我想触发一个 bat 文件,其中包含一些可以停止特定应用程序进程的命令。要停止此应用程序进程,需要在网络驱动器上触发 cmd 文件的特定命令。所以我编写了一个将形成 PSSession 的代码,在 PSSession 形成之后,NET USE 命令应该运行。如果我首先形成 PSSession,然后手动触发命令触发 NET USE 命令,那么它可以正常工作。但是当我触发整个代码时,它不能正常运行,它会抛出错误。

NET : System error 1219 has occurred.
At line:18 char:1
+ NET USE $path /user:$user $value
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (System error 1219 has occurred.:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError

Multiple connections to a server or shared resource by the same user, using more than one user name, are not allowed. Disconnect all previous connections to the server or shared 
resource and try again.

【问题讨论】:

    标签: powershell powershell-remoting net-use


    【解决方案1】:

    问题在于Enter-PSSession 只能通过交互式 提示起作用。又名。您在提示符中输入命令。脚本/一起运行所有内容是交互式的(即,您不能开始在运行脚本的中间输入命令)。

    解决方法是使用Invoke-Command 并将您想要执行的所有内容放在一个脚本块中。这种方式可以作为非交互式命令执行。例如:

    ....
    
    $user = "NAmarshmellow"
    $server = "Desktop_10U"
    $path = "\\Users\mellow\Documents\Proj"
    $pwd = Read-Host -AsSecureString
    $bstr = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($pwd)
    $value = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($bstr)
    
    $script = {
        $user = $Using:user
        $path = $Using:path
        $value = $Using:value
    
        NET USE $path /user:$user $value
        Start-Process cmd -ArgumentList "/C C:\Users\Desktop_10U\Documents\Some\Stop.bat" -Wait
    }
    
    Invoke-Command -ComputerName $server -Credential $user -ScriptBlock $script
    
    ....
    

    【讨论】:

    • 谢谢你的解决方案很恰当!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-15
    • 2017-11-20
    • 2018-01-18
    • 1970-01-01
    • 1970-01-01
    • 2019-06-27
    • 2014-04-05
    相关资源
    最近更新 更多