笔记:配置vscode作为powershell开发环境

Powershell ISE用于代码测试与交互还可,但是如果用来写脚本就觉得很不舒服,所以要转往vscode,本文将记录vscode安装调试,以备忘。

安装调试vscode

  1. 配置Powershell Gallery仓库
  • Powershell 版本V5或更高,执行下面命令即可
# I add the switch Trusted because I trust all the modules and scripts from Powershell Gallery
Register-PSRepository -Default -InstallationPolicy Trusted
  • Powershell版本低于V5
> Register-PSRepository -Name PSGallery -SourceLocation https://www.powershellgallery.com/api/v2/ -InstallationPolicy Trusted

> Get-PSRepository

Name                      InstallationPolicy   SourceLocation
----                      ------------------   --------------
PSGallery                 Trusted              https://www.powershellgallery.com/api/v2/

测试仓库

# Search a module which name is like poshrs*
> find-module poshrs*

Name                           Version          Source           Summary
----                           -------          ------           -------
PoshRSJob                      1.7.4.4          PSGallery        Provides an alternative to PSjobs with greater performance and less overhead to run commands in ...

# Install the module without admin privileges
> find-module poshrs* | install-module -Scope CurrentUser

2.为Powershell配置.Net包管理器(NuGet

# I also add the Trusted switch
Register-PackageSource -Name Nuget -Location "http://www.nuget.org/api/v2" –ProviderName Nuget -Trusted

由下面可知,当前机器装的NuGet版本是V2,因此只能使用V2 API

> Get-PackageProvider

Name                     Version          DynamicOptions
----                     -------          --------------
msi                      3.0.0.0          AdditionalArguments
msu                      3.0.0.0
NuGet                    2.8.5.208        Destination, ExcludeVersion, Scope, SkipDependencies, Headers, FilterOnTag, ...
PowerShellGet            1.0.0.1          PackageManagementProvider, Type, Scope, AllowClobber, SkipPublisherCheck, In...
Programs                 3.0.0.0          IncludeWindowsInstaller, IncludeSystemComponent

测试NuGet

> Get-PackageSource

Name                             ProviderName     IsTrusted  Location
----                             ------------     ---------  --------
Nuget                            NuGet            True       http://www.nuget.org/api/v2
PSGallery                        PowerShellGet    True       https://www.powershellgallery.com/api/v2/

# install the latest version of GitForWindows without admin privileges
find-package gitforwindows | install-package -Scope CurrentUser

# install the latest version of Python without admin privileges
find-package python | install-package -Scope CurrentUser

# find the path of Python installation
get-package python | % source

# You need to add manually the package executable path to your USER PATH.
# To get the current USER Path
[System.Environment]::GetEnvironmentVariable('Path', 'User')

# To set the current USER Path
[System.Environment]::SetEnvironmentVariable('Path', $newPathInSingleStringSeparatedByColumn, 'User')
  1. 安装Windows包管理器Chocolatey
# modify powershell executive policy
> Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope LocalMachine -Force

# Install Chocolatey online, need to restart powershell after Chocolatey installation
> Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))
# Verify if Chocolatey was installed successfully

cPS C:\Windows\system32> choco --version 
0.10.15
  1. 使用chocolatey安装vscode,然后安装扩展插件后配置vscode
    choco install vscode -y
  • 验证是否安装成功
PS C:\Windows\system32> choco list --local-only 
Chocolatey v0.10.15
2 validations performed. 1 success(es), 1 warning(s), and 0 error(s).

Validation Warnings:
 - A pending system reboot request has been detected, however, this is
   being ignored due to the current command being used 'list'.
   It is recommended that you reboot at your earliest convenience.

chocolatey 0.10.15
chocolatey-core.extension 1.3.5.1
DotNet4.5.2 4.5.2.20140902
vscode 1.52.1
vscode.install 1.52.1
5 packages installed.
  • 启动vscode,安装powershell支持插件
    Ctrl + , 打开终端模式,在当前终端中输入以下命令,安装插件
code --install-extension ms-vscode.powershell
code --install-extension vscode-icon-team.vscode-icons
code --install-extension daylerees.rainglow
  • Ctrl + Shift + P 调出vscode命令模式,找到如下图命令,回车
image.png

输入如下代码,完成配置

{
    "workbench.colorTheme": "Codecourse Contrast (rainglow)",
    "workbench.iconTheme":"vscode-icons",
    "files.defaultLanguage": "powershell",
    "editor.formatOnType": true,
    "editor.formatOnPaste": true,
    "powershell.integratedConsole.focusConsoleOnExecute": true,
    "window.zoomLevel": 0,
    "editor.mouseWheelZoom": true
}

如果终端模式有时无相应,可以将下面代码加入上面的JSON代码快中

"powershell.integratedConsole.showOnStartup": false,
"terminal.explorerKind": "external",
"powershell.integratedConsole.focusConsoleOnExecute": false

安装配置Git

配置ssh用来实现快捷访问github

1.确保安装openss-client组件,以提供ssh客户端功能

PS C:\Users\huzx\powershell> Get-WindowsCapability -online | ? {$_.name -match 'openssh.client'} 

Name  : OpenSSH.Client~~~~0.0.1.0
State : Installed

本文实验主机已经安装,如果未安装,请执行以下命令

$OpenSSHClient= Get-WindowsCapability -online | ? {$_.name -match 'openssh.client'} 
Add-WindowsCapaability -online -Name $OpenSSHClient.Name

确保ssh-agent服务运行,并将其设置为自动启动

$SSHAgentSvc=Get-Service -Name 'ssh-agent' 
Set-Service -Name $SSHAgentSvc.Name -StartupType Automatic
Start-Service -Name $SSHAgentSvc.Name

本文实验主机已确认

PS C:\Users\huzx\powershell> Get-Service -Name ssh-agent 


Status   Name               DisplayName
------   ----               -----------
Running  ssh-agent          OpenSSH Authentication Agent
  1. 创建ssh key,使用ssh-keygen命令生成ssh key密钥对,后面我们将会吧公钥上传到github实现ssh快捷访问
    ssh-keygen -t RSA -b 2048
    只需一路回车,生成密钥对即可,执行完成后,将会在如下路径生成相关文件
    $HOME\.ssh\id_rsa
PS C:\Users\huzx\.ssh> ls


    Directory: C:\Users\huzx\.ssh


Mode                LastWriteTime         Length Name                                                                                                                                                                                                            
----                -------------         ------ ----                                                                                                                                                                                                            
-a----        1/27/2021   1:20 PM             51 config                                                                                                                                                                                                          
-a----        1/27/2021  11:04 AM           1679 id_rsa                                                                                                                                                                                                          
-a----        1/27/2021  11:04 AM            403 id_rsa.pub                                                                                                                                                                                                      

使用下面命令将当前密钥对添加到ssh-agent服务
ssh-add

  1. 将公钥上传至Github
  • 复制公钥到粘贴板
    Get-Content -Path $HOME\.ssh\id_rsa.pub | Set-Clipboard - (也可以记事本打开复制文件中的内容)
  • 打开Github添加ssh key页面,然后将公钥内容复制到输入框中,标题自定义
    Start-Process 'https://github.com/settings/ssh/new' -(也可以浏览器打开Gihub,点击头像选择settings,然后在设置界面的左上侧选择SSH and GPG keys,然后粘贴公钥和自定义标题完成后如下
    image.png
  • 测试是否可以快速链接到Github
C:\Users\huzx\powershell>ssh -T git@github.com
warning: agent returned different signature type ssh-rsa (expected rsa-sha2-512)
Hi buffallos! You've successfully authenticated, but GitHub does not provide shell access.
安装配置Git
  • 安装Git
PS C:\Users\huzx\.ssh> choco install git -y 
Chocolatey v0.10.15
Installing the following packages:
git
By installing you accept licenses for the packages.

Progress: Downloading git 2.30.0.2... 10%
Progress: Downloading git 2.30.0.2... 32%
Progress: Downloading git 2.30.0.2... 53%
Progress: Downloading git 2.30.0.2... 75%
Progress: Downloading git 2.30.0.2... 97%
Progress: Downloading git 2.30.0.2... 100%

git.install v2.30.0.2 [Approved]
git.install package files install completed. Performing other installation steps.
Killing any running git ssh-agent instances
Using Git LFS
Installing 64-bit git.install...
git.install has been installed.
git.install installed to 'C:\Program Files\Git'
  git.install can be automatically uninstalled.
Environment Vars (like PATH) have changed. Close/reopen your shell to
 see the changes (or in powershell/cmd.exe just type `refreshenv`).
 The install of git.install was successful.
  Software installed to 'C:\Program Files\Git\'

git v2.30.0.2 [Approved]
git package files install completed. Performing other installation steps.
 The install of git was successful.
  Software install location not explicitly set, could be in package or
  default install location if installer.

Chocolatey installed 2/2 packages. 
 See the log for details (C:\ProgramData\chocolatey\logs\chocolatey.log).
  • 初始化本地仓库
# 创建本地仓库所在folder
> mkdir $home\powershell
# 配置环境
> git config --global user.name "buffallos"
> git config --global user.email "p270640624@gmail.com"
> git config --list 
# 初始化本地仓库
> cd $home\powershell
> git init
  • 使用GitHub
    在仓库目录新建测试文件test.txt ,执行git status可以看到新文件状态为untracked files
PS C:\Users\huzx\powershell> git status 

On branch master
Your branch is up to date with 'origin/master'.

Untracked files:
  (use "git add <file>..." to include in what will be committed)
        test.txt

nothing added to commit but untracked files present (use "git add" to track)
PS C:\Users\huzx\powershell> 

使用git add将其添加到本地仓库

PS C:\Users\huzx\powershell> git add test.txt 

PS C:\Users\huzx\powershell> git status 

On branch master
Your branch is up to date with 'origin/master'.

Changes to be committed:
  (use "git restore --staged <file>..." to unstage)
        new file:   test.txt

PS C:\Users\huzx\powershell> 

提交到仓库

PS C:\Users\huzx\powershell> git commit -m 'new files'

[master 4807203] new files
 1 file changed, 0 insertions(+), 0 deletions(-)
 create mode 100644 test.txt
PS C:\Users\huzx\powershell> 

如果不想继续跟踪一个已git add到添加到了暂存区,可以使用git rm进行移除出暂存区

PS C:\Users\huzx\powershell> git rm test.txt 

rm 'test.txt'
PS C:\Users\huzx\powershell> git status 

On branch master
Your branch is ahead of 'origin/master' by 1 commit.
  (use "git push" to publish your local commits)

Changes to be committed:
  (use "git restore --staged <file>..." to unstage)
        deleted:    test.txt

PS C:\Users\huzx\powershell> git commit -m 'remove test.txt'

[master 0cea750] remove test.txt
 1 file changed, 0 insertions(+), 0 deletions(-)
 delete mode 100644 test.txt
PS C:\Users\huzx\powershell> git status 

On branch master
Your branch is ahead of 'origin/master' by 2 commits.
  (use "git push" to publish your local commits)

nothing to commit, working tree clean
PS C:\Users\huzx\powershell> ls



    Directory: C:\Users\huzx\powershell


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----        1/27/2021  11:11 AM             30 README.md
-a----        1/27/2021   2:59 PM              3 test.ps1

内容修改后,可以重复git add和git commit将修改提交至本地仓库
注意:git add 和 git commit -m '描述信息',vscode中对应命令操作,将由source control中的按钮取代

关联远程仓库和本地仓库
  • 初始化远程仓库
    PS C:\Users\huzx\powershell> git remote add origin git@github.com:buffallos/PowerShell.git
  • 查看远程仓库
PS C:\Users\huzx\powershell> git remote -v 
origin  git@github.com:buffallos/PowerShell.git (fetch)
origin  git@github.com:buffallos/PowerShell.git (push)
  • 拉取远程仓库内容到本地仓库
c:\Users\huzx\powershell>git pull
There is no tracking information for the current branch.
Please specify which branch you want to merge with.
See git-pull(1) for details.

    git pull <remote> <branch>

If you wish to set tracking information for this branch you can do so with:

    git branch --set-upstream-to=origin/<branch> master

如果远程仓库非空,可以使用下面的命令强制将远程仓库中的内容拉取过来

c:\Users\huzx\powershell>git pull origin master --allow-unrelated-histories
Warning: Permanently added the RSA host key for IP address '13.250.177.223' to the list of known hosts.
From github.com:buffallos/PowerShell
* branch            master     -> FETCH_HEAD

c:\Users\huzx\powershell>dir
 Volume in drive C is OSDisk
 Volume Serial Number is A8CE-2457

 Directory of c:\Users\huzx\powershell

01/27/2021  22:57    <DIR>          .
01/27/2021  22:57    <DIR>          ..
01/27/2021  22:57                30 README.md
01/27/2021  22:57                 3 test.ps1
01/27/2021  22:28                 0 test1.txt
              3 File(s)             33 bytes
              2 Dir(s)  159,318,532,096 bytes free

最后,打开vscode,在左侧上部分选中source control按钮,然后打开本地仓库所在目录即可,以后慢慢再熟悉git用法。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 215,923评论 6 498
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,154评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 161,775评论 0 351
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,960评论 1 290
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,976评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,972评论 1 295
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,893评论 3 416
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,709评论 0 271
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,159评论 1 308
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,400评论 2 331
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,552评论 1 346
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,265评论 5 341
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,876评论 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,528评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,701评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,552评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,451评论 2 352

推荐阅读更多精彩内容