在PowerShell脚本中跳出bash代码序列

问题描述:

我需要从PowerShell连接到Linux机器,获取一些与名称匹配的文件夹,然后删除它们(如果您问为什么,请为测试环境进行清理)。在PowerShell脚本中跳出bash代码序列

要做到这一点,我使用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将不执行这些类型的语句因为它是自己的?或者,也许是另一种方法?

+0

'-Command'想'串'而不是'ScriptBlock'。是的,'ScriptBlock'可以自动转换为'string',但首先必须使用PowerShell语法规则进行分析。 – PetSerAl

$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 

试试这样。

+0

这应该是PowerShell在这里字符串? – PetSerAl

+0

是的,这就是它。 – 4c74356b41

+1

它使用'@“'和'”@'作为分隔符。 – PetSerAl