PowerShell

PowerShell 使用指南

安装/升级

Windows

第三方包管理工具:Chocolatey,安装需要管理员权限。

# 管理员模式运行
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'))
# 安装 windows 版开发工具
choco install -y vim git

MacOS

# 安装
brew cask install powershell

# 升级
brew update
brew cask upgrade powershell

Ubuntu 16

通过 .NET Core SDK 安装 PowerShell:

wget -q https://packages.microsoft.com/config/ubuntu/16.04/packages-microsoft-prod.deb -O packages-microsoft-prod.deb
sudo dpkg -i packages-microsoft-prod.deb

sudo apt-get install -y gpg
wget -qO- https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > microsoft.asc.gpg
sudo mv microsoft.asc.gpg /etc/apt/trusted.gpg.d/
wget -q https://packages.microsoft.com/config/ubuntu/16.04/prod.list
sudo mv prod.list /etc/apt/sources.list.d/microsoft-prod.list
sudo chown root:root /etc/apt/trusted.gpg.d/microsoft.asc.gpg
sudo chown root:root /etc/apt/sources.list.d/microsoft-prod.list
sudo apt-get install -y apt-transport-https
sudo apt-get update
sudo apt-get install dotnet-sdk-3.0

dotnet tool install --global PowerShell

常用命令

PowerShell 开关 -proxy "http://192.168.1.111:8118" 可以用来设置代理:

命令 作用
$PSVersionTable 确认 PowerShell 版本
Get-Command kubectl 巡查命令行位置,= Linux 的 which

模块相关

命令 作用
Get-PSRepository 巡查软件仓库
Get-InstalledModule 巡查已安装模块
Update-Module 更新已安装模块
Install-Module PowerShellGet -Force 安装官方扩展管理工具

配置

命令 作用
netsh winhttp set proxy "192.168.1.111:8118" 设置/取消代理
netsh winhttp reset proxy

字符串

命令 作用
| Select-String -Pattern KEY_WORDS 在管道传入内容中搜索

网络

命令 作用
Invoke-WebRequest -Uri www.google.com 类 curl 命令

Azure

# 登陆 Azure 中国版账号
Connect-AzAccount -Environment AzureChinaCloud

常见错误

模块无法更新

PackageManagement\Install-Package : Unable to find repository 'https://www.powershellgallery.com/api/v2/'. Use Get-PSRepository to see all available repositories.
At C:\Program Files\WindowsPowerShell\Modules\PowerShellGet\1.0.0.1\PSModule.psm1:2089 char:20
+ ...           $sid = PackageManagement\Install-Package @PSBoundParameters
+                      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (Microsoft.Power....InstallPackage:InstallPackage) [Install-Package], Exception
    + FullyQualifiedErrorId : SourceNotFound,Microsoft.PowerShell.PackageManagement.Cmdlets.InstallPackage
# 添加官方库正确地址
Register-PSRepository -Name PSGalleryV2Slash -SourceLocation https://www.powershellgallery.com/api/v2/ -InstallationPolicy Trusted
Author: njun
njun's picture
Updated: 2020/05/03