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编辑的程序名。

相关推荐
console.log('npc')8 小时前
Git 冲突与 AI 协助指南
前端·人工智能·git·大模型
技术不好的崎鸣同学13 小时前
第一章:PEB结构解析与内存定位
windows·安全·系统安全
重生之我来学Python16 小时前
Git-SVN 混合开发,从入门到精通!
开发语言·git·svn·github
江湖人称菠萝包17 小时前
【Windows】《深入浅出Windows API程序设计:编程基础篇》笔记-Chapter1-基础知识
windows·笔记
白山编程大哥17 小时前
Java 迭代器接口详解:从 Iterator 到 ListIterator 的完整指南
java·开发语言·windows
一叶龙洲17 小时前
Ubuntu从图标到卸载应用
linux·windows·ubuntu
江湖人称菠萝包17 小时前
【Windows】《深入浅出Windows API程序设计:编程基础篇》笔记-Chapter2-Windows窗口程序
windows·笔记
笨笨饿19 小时前
#137_死机恢复现场_Armino平台AP系统swd调试
git·python·stm32·单片机·嵌入式硬件·物联网·vim
King of fraud19 小时前
Git 入门:从零开始的版本控制之旅
git
奈斯先生Vector19 小时前
AIGC 视频生成实战:用 Kling Video 拆解文生视频、图生视频与完整工作流
开发语言·人工智能·windows·python·aigc·音视频