欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

powershell 如何执行 dos 命令 AG chatgpt 有大用

PowerShell 可以执行 DOS 命令(cmd 命令)的方式有多种,以下是 常用的五种方法,从简单到高级:


🔹 方法1:直接运行 .bat / .cmd 文件

直接调用.bat.cmd文件:

powershell
& "C:\path\to\your\script.bat"

powershell
Start-Process -FilePath "cmd.exe" -ArgumentList "/c C:\path\to\your\script.bat"

🔹 方法2:直接运行 DOS 命令

在 PowerShell 中运行单个 DOS 命令:

powershell
cmd /c "echo Hello, DOS!"

示例(列目录):

powershell
cmd /c "dir C:\"

✅ 说明:

  • cmd /c = 执行完成后关闭窗口

  • cmd /k = 执行完成后保持窗口(类似手动打开 cmd)


🔹 方法3:Start-Process 启动 CMD 命令

适合运行后台命令,避免阻塞当前会话:

powershell
Start-Process -FilePath "cmd.exe" -ArgumentList "/c dir C:\ > C:\dirlist.txt" -NoNewWindow

选项说明

  • -NoNewWindow = 不弹出新窗口(静默运行)

  • -WindowStyle Hidden = 完全隐藏运行


🔹 方法4:使用 Invoke-Expressioniex

适用于动态命令字符串:

powershell
$command = "ping 8.8.8.8" Invoke-Expression $command

⚠ 注意:Invoke-Expression 存在安全风险,如果运行不受信任的输入,可能导致恶意代码执行!


🔹 方法5:PowerShell 调用 CMD 并获取返回值

powershell
$output = cmd /c "dir C:\Windows" $output  # 查看命令输出

进阶用法:管道传递数据

powershell
"hostname", "ipconfig" | ForEach-Object { cmd /c $_ }

(逐个执行 hostname 和 ipconfig


📌 常用场景

✅ 场景1:运行 dir 并保存结果

powershell
cmd /c "dir C:\ > C:\dirlist.txt"

✅ 场景2:后台运行 ping

powershell
Start-Process -FilePath "cmd.exe" -ArgumentList "/c ping google.com -t > C:\pinglog.txt" -WindowStyle Hidden

✅ 场景3:批量执行 cmd 命令

powershell
"ipconfig", "systeminfo", "netstat -an" | ForEach-Object {    Write-Host "正在执行: $_" -ForegroundColor Green    cmd /c $_ }

📚 最佳实践

  1. 如需执行简单的 DOS 命令,用 cmd /c 最高效

  2. 如需隐藏窗口或后台运行,用 Start-Process

  3. 避免 Invoke-Expression(有安全风险),除非能确保输入可信。

  4. PowerShell 比 DOS 更强大,尽量使用 Get-ChildItem(替代 dir)、Test-NetConnection(替代 ping)等 PowerShell 原生命令。


🏆 总结

方法适合场景示例
cmd /c直接运行命令cmd /c "dir C:\"
Start-Process后台运行、隐藏窗口Start-Process cmd -Arg "/c ping 8.8.8.8" -NoNewWindow
& 或直接调 .bat运行批处理文件& "script.bat"
Invoke-Expression动态执行命令(谨慎!)iex "ping 8.8.8.8"
管道传递批量执行命令"ipconfig", "hostname" | % { cmd /c $_ }

推荐优先使用 PowerShell 原生命令,仅在必须时才调用 DOS 方法。


普通分类: