笔记:配置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用法。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容