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

问题描述 投票:0回答:1
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个回答
0
投票

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

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

....
© www.soinside.com 2019 - 2024. All rights reserved.