简体   繁体   English

在Powershell脚本中转​​义bash代码序列

[英]Escaping bash code sequence inside a powershell script

I need to connect from PowerShell to a Linux machine, get some folders that match a name and afterwards delete them (if you're asking why, cleanup for a test environment). 我需要从PowerShell连接到Linux计算机,获取一些与名称匹配的文件夹,然后删除它们(如果您问为什么,请清理测试环境)。

To accomplish this, I'm using the SSH.NET library (details here ) and my script looks like this so far: 为此,我使用了SSH.NET库( 在此处进行详细说明),到目前为止,我的脚本如下所示:

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}

Everything works fine until I reach the point where I need to loop through my backupsToDelete array. 一切正常,直到到达需要遍历backupsToDelete阵列的位置backupsToDelete It seems that for some reason, PowerShell is treating the for loop as it's own statement and not a bash one, everything resulting in an error: 似乎出于某种原因,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

Is there any way to tell PowerShell to not execute these kind of statements as it's own? 有什么方法可以告诉PowerShell自己不要执行这些语句? Or maybe a different approach? 还是不同的方法?

$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

try like so. 尝试这样。

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

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