从PowerShell运行Linux命令

时间:2017-09-08 05:08:16

标签: linux powershell automation

我能够在Linux上运行以下代码来成功获取未安装的磁盘。

alldisks=`/sbin/sfdisk -s | grep -v 'total' | awk -F':' '{print $1}'`
unmounted_disks=""

for disk in $alldisks
do
  /sbin/blkid -o list | grep -q "$disk"
  if [ $? -ne 0 ]; then
    unmounted_disks="$unmounted_disks $disk"
  fi
done

echo $unmounted_disks

但我正在通过使用PowerShell的工作簿自动执行此操作。在使用New-SSHSession连接后,我尝试了以下发送到Linux的方式:

**$script** = ('alldisks=`/sbin/sfdisk  -s | grep -v ''total'' | awk -F '':'' ''{print $1}''`
               unmounted_disks=""
               echo $unmounted_disks
               for disk in $alldisks
               do /sbin/blkid -o list | grep -q ''$disk''
               `n
               if [ $? -ne 0 ]
                 then unmounted_disks=''$unmounted_disks $disk''
               fi
               done
               echo $unmounted_disks')
$output = **Invoke-SSHCommand** -Index $session.SessionId **-Command $script** -TimeOut 900 -ErrorAction Stop

我得到以下错误:

  

bash:-c:第8行:意外标记“fi”附近的语法错误   bash:-c:第8行:`fi'

1 个答案:

答案 0 :(得分:0)

为您的脚本使用here-string

$script = @'
alldisks=`/sbin/sfdisk  -s | grep -v 'total' | awk -F ':' '{print $1}'`
unmounted_disks=""
echo $unmounted_disks
for disk in $alldisks
do
  /sbin/blkid -o list | grep -q "$disk"
  if [ $? -ne 0 ]; then
    unmounted_disks="$unmounted_disks $disk"
  fi
done
echo $unmounted_disks
'@