Windows下利用PowerShell实现Git自动推送

1. 背景

对一名开发者来说,办公和家里都有编程环境,并且都需要时刻保持同步,往常完全靠个人记忆,手工同步,这导致有时候会遗忘。此刻,如果有一个定时任务帮我在某个时刻,将 Git 自动同步,这将是一种不同于以往任何一个体验。

2. 使用插件

2.1. Windows

办公环境都是 Windows ,办公室用的 Windows 10,家里用的 Windows 11

2.2. VSCode

Visual Studio Code(简称 VS Code)是一款由微软开发的轻量级、跨平台代码编辑器,支持多种编程语言和扩展功能,深受开发者喜爱 ,使用 VSCode 开发调测PS文件。

2.3. PowerShell

PowerShell 是由微软开发的一个命令行环境和脚本语言,也是一种跨平台的任务自动化解决方案,用于系统管理和配置管理,由命令行 shell、脚本语言和配置管理框架组成。

具体安装 请参考 在 Windows 上安装 PowerShell

此处使用 PowerShell-7.5 作为执行的环境,下载地址 PowerShell-7.5.4-win-x86.zip

3. 实现步骤

3.1. PS代码

ps1 复制代码
# 文件名:autoGitPush.ps1
Function gitPush {
    # 将脚本放置在项目根路径
    if ($PSVersionTable.PSVersion.Major -ge 3) {
        # PowerShell 3.0 或更高版本
        $ScriptPath = $PSCommandPath
    } else {
        # PowerShell 2.0 或更低版本
        $MyInvocation = (Get-Variable MyInvocation).Value
        $ScriptPath = $MyInvocation.MyCommand.Definition
        $ScriptDir = Split-Path -Parent $ScriptPath
    }

    $ScriptDir = Split-Path -Path $ScriptPath -Parent
    Write-Output $ScriptDir

    Set-Location $ScriptDir # 切换到项目路径
    $now = Get-Date # 获取时间日期对象
    $msg = " The Commit Message==>  " + $now.ToString('yyyy-MM-dd HH:mm:ss') + "==="#
    # 将提交信息输出到日志文件gitpush.log
    $msg | Out-File -FilePath .\gitpush.log -Append -Encoding utf8
    Write-Output $msg
    # 将代码的相关信息输出到日志文件gitpush.log
    git status >> .\gitpush.log 
    git add . >> .\gitpush.log
    git commit -m $msg  >> .\gitpush.log
    git push origin main  >> .\gitpush.log
}

gitPush # 运行函数

3.2. 自动化任务配置

打开任务计划窗口
选择创建任务
  • 选择创建任务,并参考下图进行配置。
  • 新建触发器任务
  • 操作

程序或脚本 选择下载的 PowerShell-7.5.4-win-x64 下的 pwsh.exe

添加参数(可选)(A) : -File G:\sam-abram\sam-abram.ps1 其中 sam-abram.ps1 为 Vscode编辑的程序名。

相关推荐
郡杰6 小时前
Git基础与开发平台搭建
git·后端
binbin_526 小时前
Flutter 开发鸿蒙实战:Windows 环境下从 HAP 构建到四 Tab 页面运行
windows·flutter·harmonyos
ylscode7 小时前
微软推送KB5095189:Windows 11 OOBE开箱即用体验迎来新一轮优化
windows·microsoft
Fer_David7 小时前
解决Windows无法在微软商店安装CodeX问题
windows
钟智强8 小时前
我警告了 329 天
git·php·wordpress·webshell
忧虑的小蚂蚁9 小时前
dll文件32位64位检测工具以及Windows文件夹SysWow64的坑
windows
乐观的冷风9 小时前
我们需要将文件添加到暂存区才能提交,而移除文件后是无法添加到暂存区的,那么怎么移除一个文件让GIT不再将其纳入版本控制呢?上图中GIT已经给出了说明:
git
tjl521314_2110 小时前
Git SSH Host Key Verification Failed 问题排查与解决
运维·git·ssh
杨云龙UP11 小时前
Windows SQL Server 备份无法传输至异地共享目录排查处理
运维·服务器·数据库·windows·共享·smb·异地备份传输
AI行业学习11 小时前
Notepad++ 官方纯净下载+完整安装教程(Windows)【2026.7.5】
开发语言·windows·python·前端框架·html·notepad++