只有在服务器上形成 pssession 后,如何在远程服务器上触发 bat 文件

How to trigger a bat file on remote server only after the pssession is formed on the server

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.

问题是 Enter-PSSession 只能通过 interactive 提示工作。又名。您在提示符中输入命令。 script/running 一切都不是 交互的(即你不能开始在 运行 脚本中间输入命令)。

解决方法是使用 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

....