You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在PowerShell中实现Bash的| while read file do/done逻辑?

Bash 管道循环到 PowerShell 的转换方法

原Bash脚本

cd tmp &&
inotifywait -me close_write,create,move --format %f *.tmp | while read file
do  rclone move "$file" dropbox:
done

转换后的PowerShell实现

下面是对应逻辑的PowerShell写法,核心是替换Bash的while read管道循环:

方式一:使用ForEach-Object(PowerShell惯用写法)

# 切换到tmp目录,失败则终止后续执行
Set-Location tmp -ErrorAction Stop;
# 监听文件变化,将输出逐个传入循环处理
inotifywait -me close_write,create,move --format %f *.tmp | ForEach-Object {
    rclone move $_ dropbox:
}
  • $_是PowerShell中管道传递的当前对象,对应Bash里的$file
  • 如果需要处理带特殊字符的文件名,可写成rclone move "$_" dropbox:,和Bash逻辑一致

方式二:使用while循环读取管道内容

如果你更偏好类似Bash的while read结构,也可以这样写:

Set-Location tmp -ErrorAction Stop;
inotifywait -me close_write,create,move --format %f *.tmp | while ($file = $_) {
    rclone move $file dropbox:
}

补充说明

  • 你提到的Bash&&,PowerShell中如果要实现“前命令成功才执行后命令”,除了用-and,更规范的是用-ErrorAction Stop结合脚本块,或者用if (Set-Location tmp) { ... }
  • PowerShell中cd是Set-Location的别名,两者功能一致,使用标准命令可读性更强

内容的提问来源于stack exchange,提问作者God of Money

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 20:07:34