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

相关推荐
多来哈米1 天前
openclaw在Windows部署
windows·openclaw
视觉AI1 天前
【踩坑实录】Windows ICS 共享网络下,国产化盒子 SSH 连接异常的完整分析
网络·windows·ssh
刺客xs1 天前
git 入门常用命令
大数据·git·elasticsearch
qq_246646191 天前
openclaw快速安装-windows版
windows·stm32·单片机
LostSpeed1 天前
git - github工程中不能包含大文件
git·github
pzx_0011 天前
【GIT】删除远程文件
git
sonrisa_1 天前
Python同一类不同方法中变量值的传递
开发语言·windows·python
小白_ysf1 天前
Git 命令操作完整指南(实际工作中常用命令)
git·代码上传
玖釉-1 天前
探索连续细节层次(Continuous LOD):深入解析 NVIDIA 的 nv_cluster_lod_builder
c++·windows·图形渲染
MyY_DO1 天前
第九课ida与花指令
windows·od