Skip to main content

代码片段

npm全局安装包装

function npm-g($packageName){
npm install -g $packageName --registry=https://registry.npm.taobao.org
}
npm-g <pakcageName>

powershell 基本信息

# 查看版本
$PSVERSIONTABLE

# 查看编码
[psobject].Assembly.GetTypes() | Where-Object { $_.Name -eq 'ClrFacade'} |
ForEach-Object {
$_.GetMethod('GetDefaultEncoding', [System.Reflection.BindingFlags]'nonpublic,static').Invoke($null, @())
}

$PSDefaultParameterValues结合Out-File输出到日志文件

输出log是一个永恒的话题,什么tracelistener,net4log,nlog,windows中自带的eventlog,之前在自动重定向PowerShell控制台输出到文件 也算。其实借助于PowerShell 3.0以后的PowerShell默认参数$PSDefaultParameterValues,可以让Out-File,命令也变成也简易的Log神器。

$PSDefaultParameterValues['Out-File:FilePath'] = 'mylog.txt'
$PSDefaultParameterValues['Out-File:Append'] = $true
PS> 'Log Started' | Out-File
PS> "Time=$(Get-Date)" | Out-File
PS> 'Log ended' | Out-File
PS> Get-Content .\mylog.txt
Log Started
Time=06/12/2014 11:01:05
Log ended

原文:https://www.pstips.net/psdefaultparametervalues-2.html

设置默认编码为 utf-8

// 添加到 $PROFILE 文件内
$PSDefaultParameterValues['Out-File:Encoding'] = 'utf8'

开启脚本支持

默认 win10 的脚本支持是关闭的,这一意味着所以 .ps1 的脚本文件都无法运行,会得到一个下图的错误提示:

  • 开启
# 将powershell切换为管理员模式下
set-ExecutionPolicy RemoteSigned
# 选择 Y

查看环境变量

# 查看一个环境变量
$env:{变量名}

$env:GDAL_DAYA

image-20211213133423607 image-20211213133423607

添加环境变量(临时)

# 设置一个环境变量
$env:{key}={value}

$env:GDAL_DAYA="Z:\CPS\python\Python375_64\Lib\site-packages\osgeo\data\gdal"

添加环境变量(永久)

  • 简单版

    function set_env($Name, $Value){
    [Environment]::SetEnvironmentVariable($Name, $Value, 2)
    }

    // 添加
    set_env "ELECTRON_MIRROR" "https://registry.npm.taobao.org/"

    // 删除
    set_env "ELECTRON_MIRROR" ""

    复杂版

    function Set-EnvironmentVariable
    {
    param
    (
    [string]
    [Parameter(Mandatory)]
    $Name,

    [string]
    [AllowEmptyString()]
    [Parameter(Mandatory)]
    $Value,

    [System.EnvironmentVariableTarget]
    [Parameter(Mandatory)]
    $Target
    )

    [Environment]::SetEnvironmentVariable($Name, $Value, $Target)
    }
    Set-EnvironmentVariable -Name test -Value 123 -Target User

    Set-EnvironmentVariable "test" "123" 0

获取历史记录

function cps-get-history {
$his = Get-Content (Get-PSReadLineOption).HistorySavePath
$n = $his.Length
$out = @()
for($i=0;$i -lt $n;$i++)
{
$out = $out + "$i $($his[$i])"
}

echo history count $n
return $out
}

切换电源模式

# 节电模式
powercfg -s a1841308-3541-4fab-bc81-f71556f20b4a

# 高性能模式
powercfg -s 8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c

# 平衡模式
powercfg -s 381b4222-f694-41f0-9685-ff5bb260df2e

#終極效能
powercfg -duplicatescheme e9a42b02-d5df-448d-aa00-03f14749eb61

# 列出所有模式
powercfg -aliases

surface 重启蓝牙

[CmdletBinding()] Param (
[Parameter(Mandatory=$true)][ValidateSet('Off', 'On')][string]$BluetoothStatus
)
If ((Get-Service bthserv).Status -eq 'Stopped') { Start-Service bthserv }
Add-Type -AssemblyName System.Runtime.WindowsRuntime
$asTaskGeneric = ([System.WindowsRuntimeSystemExtensions].GetMethods() | ? { $_.Name -eq 'AsTask' -and $_.GetParameters().Count -eq 1 -and $_.GetParameters()[0].ParameterType.Name -eq 'IAsyncOperation`1' })[0]
Function Await($WinRtTask, $ResultType) {
$asTask = $asTaskGeneric.MakeGenericMethod($ResultType)
$netTask = $asTask.Invoke($null, @($WinRtTask))
$netTask.Wait(-1) | Out-Null
$netTask.Result
}
[Windows.Devices.Radios.Radio,Windows.System.Devices,ContentType=WindowsRuntime] | Out-Null
[Windows.Devices.Radios.RadioAccessStatus,Windows.System.Devices,ContentType=WindowsRuntime] | Out-Null
Await ([Windows.Devices.Radios.Radio]::RequestAccessAsync()) ([Windows.Devices.Radios.RadioAccessStatus]) | Out-Null
$radios = Await ([Windows.Devices.Radios.Radio]::GetRadiosAsync()) ([System.Collections.Generic.IReadOnlyList[Windows.Devices.Radios.Radio]])
$bluetooth = $radios | ? { $_.Kind -eq 'Bluetooth' }
[Windows.Devices.Radios.RadioState,Windows.System.Devices,ContentType=WindowsRuntime] | Out-Null
Await ($bluetooth.SetStateAsync($BluetoothStatus)) ([Windows.Devices.Radios.RadioAccessStatus]) | Out-Null

一键创建、导入

通过echo指令将后面的内容直接输出成文件,且保存到用户文件夹下

# powershell
echo `
"registry=https://registry.npm.taobao.org`
sass_binary_site=https://npm.taobao.org/mirrors/node-sass/`
electron_mirror=https://npm.taobao.org/mirrors/electron/`
"> $env:USERPROFILE\.npmrc

重启wifi设备

当前脚本需要管理员权限,配合bat脚本进行提权然后调用

# 获取指定设备的实例
function Get-Device {
param (
[string]$DeviceName
)
Get-PnpDevice | Where-Object { $_.FriendlyName -eq $DeviceName }
}

# 禁用设备
function Disable-Device {
param (
[string]$InstanceId
)
Disable-PnpDevice -InstanceId $InstanceId -Confirm:$false
Start-Sleep -Seconds 1
}

# 启用设备
function Enable-Device {
param (
[string]$InstanceId
)
Enable-PnpDevice -InstanceId $InstanceId -Confirm:$false
Start-Sleep -Seconds 1
}

# 验证设备状态
function Check-DeviceStatus {
param (
[string]$DeviceName
)
$device = Get-Device -DeviceName $DeviceName
if ($device) {
return $device.Status
}
return $null
}

# 等待功能(打印提示信息)
function Wait-WithMessage {
param (
[int]$Seconds = 3
)
for ($i = 1; $i -le $Seconds; $i++) {
Write-Host "等待第 $i 秒..." -ForegroundColor Cyan
Start-Sleep -Seconds 1
}
}

# 主逻辑
function Toggle-WiFiDevice {
param (
[string]$DeviceName
)

$device = Get-Device -DeviceName $DeviceName
if (-not $device) {
Write-Host "未找到设备: $DeviceName" -ForegroundColor Red
return
}

if ($device.Status -eq "OK") {
Write-Host "设备已启用,现在尝试禁用设备..." -ForegroundColor Yellow
Disable-Device -InstanceId $device.InstanceId

$status = Check-DeviceStatus -DeviceName $DeviceName
if ($status -ne "OK") {
Write-Host "设备禁用成功。" -ForegroundColor Green
Wait-WithMessage -Seconds 3

Write-Host "尝试重新启用设备..." -ForegroundColor Yellow
Enable-Device -InstanceId $device.InstanceId

$status = Check-DeviceStatus -DeviceName $DeviceName
if ($status -eq "OK") {
Write-Host "设备已重新启用。" -ForegroundColor Green
} else {
Write-Host "设备重新启用失败,请检查设备状态。" -ForegroundColor Red
}
} else {
Write-Host "设备禁用失败,请检查权限或设备状态。" -ForegroundColor Red
}
} else {
Write-Host "设备已禁用,现在尝试启用设备..." -ForegroundColor Yellow
Enable-Device -InstanceId $device.InstanceId

$status = Check-DeviceStatus -DeviceName $DeviceName
if ($status -eq "OK") {
Write-Host "设备已成功启用。" -ForegroundColor Green
} else {
Write-Host "设备启用失败,请检查设备状态。" -ForegroundColor Red
}
}
}

# 调用主逻辑
$DeviceName = "Intel(R) Wi-Fi 6 AX201 160MHz"
Toggle-WiFiDevice -DeviceName $DeviceName