linux - 在 powershell 脚本中转义 bash 代码序列

标签 linux bash powershell

我需要从 PowerShell 连接到 Linux 机器,获取一些与名称匹配的文件夹,然后删除它们(如果你问为什么,清理测试环境)。

为此,我使用了 SSH.NET 库(详细信息 here),到目前为止我的脚本如下所示:

New-SshSession -ComputerName UbuntuMachine -Username root -Password test1234
Invoke-SshCommand -InvokeOnAll -Command {\
        cd /dev;\
        shopt -s nullglob;\
        backupsToDelete=(Nostalgia*);\
        printf "%s\n" "${backupsToDelete[@]}";\
        for i in "${backupsToDelete[@]}"\
        do\
            printf $i\
        done}

一切正常,直到我到达需要循环遍历 backupsToDelete 数组的地步。似乎出于某种原因,PowerShell 正在将 for 循环视为它自己的语句而不是 bash 语句,一切都会导致错误:

At C:\Users\Administrator\Desktop\CleanupLinux.ps1:7 char:6
+         for i in "${backupsToDelete[@]}"\
+            ~
Missing opening '(' after keyword 'for'.
    + CategoryInfo          : ParserError: (:) [], ParseException
    + FullyQualifiedErrorId : MissingOpenParenthesisAfterKeyword

有什么方法可以告诉 PowerShell 不要像它自己那样执行这些类型的语句?或者可能采用不同的方法?

最佳答案

$command = "@
{\
cd /dev;\
shopt -s nullglob;\
backupsToDelete=(Nostalgia*);\
printf "%s\n" "${backupsToDelete[@]}";\
for i in "${backupsToDelete[@]}"\
do\
   printf $i\
done}
@"

New-SshSession -ComputerName UbuntuMachine -Username root -Password test1234
Invoke-SshCommand -InvokeOnAll -Command $command

这样试试。

关于linux - 在 powershell 脚本中转义 bash 代码序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40637536/

相关文章:

powershell - 如何获取字符串格式的对象成员

powershell - 如何为Powershell控制台配置编码?

c# - 如何在 .NET Core RC2 控制台应用程序(Linux、Debian 8)中使用 System.Data?

linux - 如何在 Linux 中检查崩溃转储

linux - Linux "permission denied"的解决方案

arrays - 通过动态构造的变量名称间接分配给bash数组变量

linux - 在 bash 中是否有另一个用于循环命令历史记录的键盘快捷键?

bash - 如何使用 bash/sh shell 从容器内部终止容器进程 (PID 1)

windows - 如何获得 LAN 上事件的 IP 地址、MAC 地址和 NetBIOS 名称的列表?

Java 预装在 Windows 和 Linux 中?