使用 PowerShell 实现定时上传笔记至服务器

问题由来:平时喜欢学习些新的技术,也有随手记笔记的习惯,但是出门在外想看笔记查看某个命令什么的,却不那么方便,便想着能否将已形成的笔记放到服务器上,方便我随时使用手机查看。

总体思路:将笔记导出为 html,用 PowerShell 写一个脚本,配置成定时计划,定时同步笔记至服务器。同步工具选择 cwRsync(Windows 版本de rsync),使用 NodeJS 写个简单的前端页面配合 Nginx 展示笔记。

平常使用 Boost Note 记笔记,支持 Markdown,它可以导出为 html,然后写一个 Powershell 脚本同步本地文件到远程服务器,内容如下:

# 1.设置执行策略为 Bypass,允许执行未签名的脚本
Set-ExecutionPolicy Bypass -Scope Process -Force

# 2.定义本地和远程文件夹路径
$localFolder = "E:\Note"   # 替换为本地文件夹路径
$remoteFolder = "/opt/Note"   # 替换为远程文件夹路径
$hostname = "your-hostname" #主机名
$temp = "_assets" #相关文件后缀

# 3.设置控制台输出的颜色,格式
function writeMsg($msg, $msgColor){
  Write-Host "************** " -NoNewline
  Write-Host $msg -ForegroundColor $msgColor -NoNewline
  Write-Host  " **************`n"
}

# 4.递归查找所有 HTML 文件
cd $localFolder
$files = Get-ChildItem -Path $localFolder -Recurse -Filter *.html

foreach ($file in $files) {
    # 5.获取目录
  $directory = Split-Path $file.FullName.Substring($localFolder.Length + 1) -Parent
  $fileName = [System.IO.Path]::GetFileNameWithoutExtension($file)
    
  writeMsg "开始同步 $fileName" "DarkCyan"
  try{
    # 6.检查远程文件夹是否存在,如果不存在则创建
    if ( !(Test-Path -Path ./$directory/$fileName$temp/ -PathType Container)) {
      $command = "ssh $hostname 'mkdir -p $remoteFolder/$directory/$fileName$temp'"
      
      Invoke-Expression -Command $command
      
      Write-Host "Checking and creating $remoteFolder/$directory/$fileName$temp" -ForegroundColor DarkMagenta
    }
    # 7.同步 html 文件
    rsync -avz -e "ssh" ./$directory/$($file.name) ${hostname}:$remoteFolder/$directory/$($file.name)
    # 8.同步文件夹
    rsync -avz -e "ssh" --delete ./$directory/$fileName$temp/ ${hostname}:$remoteFolder/$directory/$fileName$temp/
  }
  catch{
    Write-Error "发生错误 $_.Exception.Message"
  }
}
# 9.将 html 中的 user-content- 替换掉,使跳转生效
ssh $hostname "find $remoteFolder -name *.html -exec sed -i 's/user-content-//' {} \; ; find $remoteFolder -name previewStyle.css -exec sed -i '/li + li {/a line-height: 1.6;' {} \;"
  • 解释下脚本内容

  • 1. Powershell 脚本执行需要修改策略模式,默认是 Restricted,不允许执行任何脚本。Get-ExecutionPolicy 可以查询当前策略模式,Set-ExecutionPolicy Restricted 修改为指定模式。其他模式包括:

    • Bypass:绕过执行策略用于测试脚本。这不是推荐的日常执行策略设置。

    • AllSigned:仅允许签名的脚本运行。

    • RemoteSigned:允许来自受信任发布者的脚本运行,并且本地脚本在首次运行前必须签名。

    • Unrestricted:允许所有脚本运行,这是最宽松的模式。

  • 2. 设置相关变量。其中 $temp 是指 html 文件中图片所在文件夹后缀名。我的笔记分为不同主题,例如 Backend, Frontend,导出 Java 的笔记就会生成一份 Java_asset 文件夹存放笔记中的图片等资源。

  • 3. 设置控制台输出的颜色,方便区分。

  • 4. 找出所有 html 文件

  • 5. 因为有些笔记不想放到服务器,没有导出,所以只同步含有 html 文件的文件夹。例如对于 E:\Note\Backend\Java.html,那么 $directory=Backend,$fileName=Java

  • 6. 每个主题放到服务器的路径是 /opt/Note/Backend/,如果不存在 Backend 则创建目录,此外,我配置了免密钥登陆服务器,所以 ssh 命令中只写了主机名,而没有写密钥或密码。在 %USERPROFILE%\.ssh\config 文件添加配置(没有则自己创建),格式如下。此后使用 PowerShell 只需要 ssh hostname

  • Host your-hostname #AAAAA为服务器主机名
    HostName 47.122.65.237 #写服务器ip地址
    User root #root为登陆用户名
    Port 22 #主机端口,默认是22
    IdentityFile E:\Aliyun\zmy-rsa-key.pem #自己生成的私钥的文件路径

    7. 使用 cwRsync 同步文件,注意:源路径使用的是相对路径,当然也可以使用绝对路径,但是需要加前缀 cygdriver,例如 cygdriver/e/Note/Backend/Java.html

  • 8. 同步文件夹,--delete 表示如果源目录没有的文件夹,服务器上也要将这个文件夹删除
  • 9. 是为了修改导出的 html 文件,我在笔记中加了目录跳转的链接,BoostNote 导出的 html 跳转不生效,最后找到原因后做了修改。后一个 find 是为了修改一下样式,因为原本样式的在手机上看着有些拥挤。BoostNote 的这个软件实际就是一个 html,可以像浏览器一样 Ctrl + Shift + I 去调试,熟悉前端的可以方便修改各种样式。

后端服务:由于需要从服务器获取有哪些 html 文件要展示(因为时不时会新增一些笔记),所以用 NodeJS express 写了一个简单的接口,去获取服务器上的 html 文件名。代码如下,比较简单,不做过多解释了。

const fs = require('fs');
const path = require('path');

const directoryPath = '/opt/Note';

function getHTMLFiles(directoryPath) {
  const result = {};

  // 读取目录
  const files = fs.readdirSync(directoryPath);

  // 遍历子文件夹
  files.forEach(file => {
    const filePath = path.join(directoryPath, file);

    // 检查是否为文件夹
    if (fs.statSync(filePath).isDirectory()) {
      // 读取文件夹中的文件
      const htmlFiles = fs.readdirSync(filePath).filter(subfile => subfile.endsWith('.html'));
      if (htmlFiles.length > 0) {
        result[file] = htmlFiles;
      }
    }
  });

  return result;
}

// 构建 API
const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors());
const port = 3000;

app.get('/DocPreview/api/html-files', (req, res) => {
  const htmlFiles = getHTMLFiles(directoryPath);
  console.log('收到一个请求,结果为:', htmlFiles);
  res.json(htmlFiles);
});

app.listen(port, () => {
  console.log(`API 服务器运行在 http://192.168.0.1:${port}`);
});

前端页面:有了 html 文件之后,就可写个简单的页面去展示了。主要是自己用,所有界面设计的很一般

<script setup>
import { onMounted, ref } from 'vue';
import { serverIP, serverPort, nodePort } from '@/tools/constant';
import axios from 'axios';
const DocPreviewApi = `${serverIP}:${nodePort}/DocPreview/api/html-files`;
const serverUrl = `${serverIP}:${serverPort}`;
const files = ref({});

onMounted(() => {
  axios.get(DocPreviewApi).then(res => {
    files.value = res.data;
  }).catch(error => {
    console.error('request failed', error);
  });
});

const urls = ref(new Map());

const openFile = (dir, file) => {
  console.log(dir, file);
  if (!file || !dir || !serverUrl) {
    console.error('Invalid file or BASE_URL');
    return;
  }

  let url = urls.value.get(file);
  if (!url) {
    url = `${serverUrl}/${dir}/${file}`;
    urls.value.set(file, url);
  }
  window.open(url);
};
</script>

<template>
  <div class="container">
    <h1 class="title">This is DocPreview</h1>
    <div class="category">
      <div class="file-list" v-for="(filesList, dir) in files" :key="dir">
        <div class="file-group">
          <span>{{ dir }}</span>
          <div class="file-buttons">
            <button v-for="file in filesList" :key="file" @click="openFile(dir, file)">
              {{ file }}
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.p1{
  padding: 10px 5px 100px 2px;
  border-color: #e31d83;
  margin: 10px 0;
  border: 20px 10px 5px 0;
  /* background-color: #40b4de; */
  color: rgb(103, 11, 179);
  font-size: 24px;
  font-weight: bold;
  text-shadow: 3px 3px 1px rgb(152, 53, 53);
}
h1 {
  font-size: 60px;
  text-align: center;
  color: red;
}
p, li{
  font-size: 16px;
  line-height: 1;
  letter-spacing: 1px;
  font-family: 'Courier New', Courier, monospace;
  /* list-style-type: none; */
}
html {
  font-size: 10px;
  /* px 表示“像素(pixel)”: 基础字号为 10 像素 */
  font-family: "Open Sans", sans-serif;
  /* 这应该是你从 Google Fonts 得到的其余输出。*/
}
#test{
  color: #0056b3;
}

.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20px;
  min-height: 100vh;
  background-color: #f5f5f5;
}

.title {
  font-size: 2rem;
  font-weight: bold;
  color: #333;
  margin-bottom: 20px;
}

.category {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  width: 100%;
  max-width: 800px;
}

.file-group {
  display: flex;
  flex-direction: row;
  align-items: center;
  gap: 10px;
  margin-bottom: 20px;
}

.file-group span {
  font-size: 1.2rem;
  font-weight: bold;
  color: #333;
}

.file-buttons {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.update-button {
  margin-top: 10px;
  margin-bottom: 20px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 5px;
  padding: 10px 20px;
  font-size: 1rem;
  cursor: pointer;
  transition: background-color 0.3s ease, box-shadow 0.3s ease;
}

.update-button.loading {
  background-color: #ccc;
  cursor: not-allowed;
}

.loading-indicator {
  font-size: 0.8rem;
  color: #666;
}

.file-buttons button {
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 5px;
  padding: 10px 20px;
  font-size: 1rem;
  cursor: pointer;
  transition: background-color 0.3s ease, box-shadow 0.3s ease;
  height: auto;
  line-height: normal;
}

.file-buttons button:hover {
  background-color: #0056b3;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}

.file-buttons button {
  transform: translateY(0);
  opacity: 1;
  transition: transform 0.3s ease-in-out, opacity 0.3s ease-in-out;
}

.file-buttons button:hover {
  transform: translateY(-2px);
  opacity: 0.9;
}

@media (max-width: 600px) {
  .container {
    padding: 10px;
  }

  .title {
    font-size: 1.5rem;
  }

  .file-group span {
    font-size: 1rem;
  }

  .file-buttons button {
    padding: 8px 16px;
  }
}
</style>

Nginx 配置:用于部署前端页面和访问静态资源。

server {
  listen       5173;
  server_name  47.122.65.237;
  location /doc-preview {
      alias /home/zmy/doc-preview/dist;
      index index.html;
      try_files $uri $uri/ /index.html;
  }
}
# 
server {
  listen       9000;
  server_name  47.122.65.237;
  charset utf-8;
  location / {
      root /opt/Note;
  }
}

定时任务:windows 直接搜索任务计划程序,新建任务,主要配置任务名称、触发时间、执行的操作,操作为:powershell -ExecutionPolicy ByPass -File E:\Note\rsync.ps1 即可。

最后的结果就是这样,访问地址:http://47.122.65.237:5173/doc-preview/

存在问题:目前在手机上使用 google 浏览器无法显示页面,不知为何,如果有知道的小伙伴欢迎告知。

喜欢的小伙伴,欢迎关注我的微信公众号:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值