我需要从 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/