简体   繁体   English

从Powershell脚本运行多个cmd命令,就像我在cmd shell中运行它一样

[英]Running multiple cmd commands from powershell script as if I was running it in cmd shell

I am trying to create a powershell script which will create a session in a remote machine and run a series of commands. 我正在尝试创建一个Powershell脚本,该脚本将在远程计算机上创建一个会话并运行一系列命令。 These commands in question are to drop a Mongodb database before deployment of code. 这些有问题的命令是在部署代码之前删除Mongodb数据库。

I have the session side working but when I try to run the cmd I get X is not recognized as the name of a cmdlet . 我有会话方面的工作,但是当我尝试运行cmd时,得到的X is not recognized as the name of a cmdlet

The process I take when I am logged into the remote machine and using cmd is: 登录到远程计算机并使用cmd时执行的过程是:

  1. 'C:\\Program Files\\MongoDB\\Server\\4.0\\bin\\mongo.exe'
  2. use <database>
  3. db.dropDatabase()

This works correctly and I am trying to run those in powershell. 这可以正常工作,我正在尝试在Powershell中运行它们。 They need to be run line by line in order to work. 他们需要逐行运行才能工作。

ps1: PS1:

$session = New-PSSession -ComputerName "remoteMachine" -Credential $cred

Enter-PSSession -Session $session

Invoke-Command -ComputerName "remoteMachine" -ScriptBlock {
    & 'C:\Program Files\MongoDB\Server\4.0\bin\mongo.exe' 
    & 'use <database>'
    & 'db.dropDatabase()'
}

Exit-PSSession
Get-PSSession | Remove-PSSession

When this is run I am getting the following errors: 运行此命令时,出现以下错误:

The term 'use Assessment' is not recognized as the name of a cmdlet, “使用评估”一词不被视为cmdlet的名称,

The term 'db.dropDatabase()' is not recognized as the name of a cmdlet, 术语“ db.dropDatabase()”未被识别为cmdlet的名称,

I managed to figure it out by looking through & 'C:\\Program Files\\MongoDB\\Server\\4.0\\bin\\mongo.exe' --help . 我通过查看& 'C:\\Program Files\\MongoDB\\Server\\4.0\\bin\\mongo.exe' --help

Rather than using multiple lines, I put the command on one line like: 而不是使用多行,而是将命令放在一行上,例如:

Invoke-Command -ComputerName "remoteMachine" -ScriptBlock {
    & 'C:\Program Files\MongoDB\Server\4.0\bin\mongo.exe' <database> --eval '<action>'
}

For example: 例如:

Invoke-Command -ComputerName "remoteMachine" -ScriptBlock {
    & 'C:\Program Files\MongoDB\Server\4.0\bin\mongo.exe' testDatabase --eval 'db.dropDatabase()'
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM