PowerShell 技能连载 - 在 PowerShell 中使用 SSH

PowerShell 6 (PowerShell Core) 终于支持 SSH 了:您可以使用 SSH 来连接非 Windows 机器来进行 PowerShell 远程操作。

如果只是需要用 SSH 连接到交换机或者其它设备,那么可以使用免费的模块。该模块为所有 PowerShell 添加了大量有用的新的 SSH 命令。以下是如何下载和安装该模块的方法:

1
Install-Module -Name posh-ssh -Repository PSGallery -Scope CurrentUser

要列出所有新的命令,请运行以下代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
PS C:\> (Get-Command -Module posh-ssh).Name
Get-PoshSSHModVersion
Get-SFTPChildItem
Get-SFTPContent
Get-SFTPLocation
Get-SFTPPathAttribute
Get-SFTPSession
Get-SSHPortForward
Get-SSHSession
Get-SSHTrustedHost
Invoke-SSHCommand
Invoke-SSHCommandStream
Invoke-SSHStreamExpectAction
Invoke-SSHStreamExpectSecureAction
New-SFTPFileStream
New-SFTPItem
New-SFTPSymlink
New-SSHDynamicPortForward
New-SSHLocalPortForward
New-SSHRemotePortForward
New-SSHShellStream
New-SSHTrustedHost
Remove-SFTPItem
Remove-SFTPSession
Remove-SSHSession
Remove-SSHTrustedHost
Rename-SFTPFile
Set-SFTPContent
Set-SFTPLocation
Set-SFTPPathAttribute
Start-SSHPortForward
Stop-SSHPortForward
Test-SFTPPath
Get-SCPFile
Get-SCPFolder
Get-SFTPFile
New-SFTPSession
New-SSHSession
Set-SCPFile
Set-SCPFolder
Set-SFTPFile

PowerShell 技能连载 - 管理 Lenovo BIOS 设置(第 4 部分)

在前一个技能中我们演示了如何读取和改变 Lenovo 计算机的 BIOS 设置。例如,以下代码禁止 WakeOnLan:

1
2
3
4
5
6
7
#requires -RunAsAdministrator

$currentSetting = Get-WmiObject -Class Lenovo_SetBiosSetting -Namespace root\wmi
$currentSetting.SetBiosSetting('WakeOnLAN,Disable').return

$SaveSettings = Get-WmiObject -Class Lenovo_SaveBiosSettings -Namespace root\wmi
$SaveSettings.SaveBiosSettings().return

如果某个 BIOS 设置是被密码保护的,以下代码演示如何更改一个受 BIOS 密码保护的设置:

1
2
3
4
5
6
7
8
#requires -RunAsAdministrator
$BIOSPassword = "topSecret"

$currentSetting = Get-WmiObject -Class Lenovo_SetBiosSetting -Namespace root\wmi
$currentSetting.SetBiosSetting("WakeOnLAN,Disable,$BIOSPassword,ascii,us").return

$SaveSettings = Get-WmiObject -Class Lenovo_SaveBiosSettings -Namespace root\wmi
$SaveSettings.SaveBiosSettings("$BIOSPassword,ascii,us").return

请注意该密码仅在该设置项受 BIOS 密码保护的情况下生效。如果实际中没有密码而您输入了密码,它并不会被验证,而且改动会生效。

PowerShell 技能连载 - 管理 Lenovo BIOS 设置(第 3 部分)

在前一个技能中我们介绍了如何在 PowerShell 中管理 Lenovo BIOS。通常,只需要管理单个设置。请注意某些操作需要管理员特权。

以下是转储所有可用设置名称的代码。请注意这些名字是大小写敏感的:

1
2
3
4
$currentSetting = Get-WmiObject -Class Lenovo_BiosSetting -Namespace root\wmi
$currentSetting.CurrentSetting |
Where-Object { $_ } |
ForEach-Object { $_.Split(',')[0] }

一旦您知道了想要操作的设置项的名称,就可以用这段代码来读取设置:

1
2
3
4
$Settingname = "WakeOnLAN"

$currentSetting = Get-WmiObject -Class Lenovo_BiosSetting -Namespace root\wmi -Filter "CurrentSetting LIKE '%$SettingName%'"
$currentSetting.CurrentSetting

以下代码转储某个指定设置的所有合法值:

1
2
3
4
5
6
7
#requires -RunAsAdministrator

# this is case-sensitive
$Setting = "WakeOnLAN"

$selections = Get-WmiObject -Class Lenovo_GetBiosSelections -Namespace root\wmi
$selections.GetBiosSelections($Setting).Selections.Split(',')

以下是如何将一个设置改为一个新的值(例如,禁止 WakeOnLan):

1
2
3
4
5
6
7
#requires -RunAsAdministrator

$currentSetting = Get-WmiObject -Class Lenovo_SetBiosSetting -Namespace root\wmi
$currentSetting.SetBiosSetting('WakeOnLAN,Disable').return

$SaveSettings = Get-WmiObject -Class Lenovo_SaveBiosSettings -Namespace root\wmi
$SaveSettings.SaveBiosSettings().return

PowerShell 技能连载 - 管理 Lenovo BIOS 设置(第 2 部分)

在前一个技能中,我们解释了如何转储 Lenovo 计算机的 BIOS 设置。要调整设置,您需要了解某个设置支持的各种选项。以下是一段转储某个(Lenovo 电脑的)BIOS 设置的所有可选项的代码:

1
2
3
4
5
6
7
#requires -RunAsAdministrator

# this is case-sensitive
$Setting = "WakeOnLAN"

$selections = Get-WmiObject -Class Lenovo_GetBiosSelections -Namespace root\wmi
$selections.GetBiosSelections($Setting).Selections.Split(',')

请注意这段代码需要管理员特权。并且该设置名称是大小写敏感的。结果类似这样:

Disable
ACOnly
ACandBattery
Enable

这可能是一个显示如何获取当前 BIOS 设置,以及合法设置的列表的复杂示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#requires -RunAsAdministrator

$selections = Get-WmiObject -Class Lenovo_GetBiosSelections -Namespace root\wmi

Get-WmiObject -Class Lenovo_BiosSetting -Namespace root\wmi |
Where-Object CurrentSetting |
ForEach-Object {
$parts = $_.CurrentSetting.Split(',')
[PSCustomObject]@{
CurrentSetting = $parts[0]
Status = $parts[1]
Active = $_.Active
AvailableSettings = $selections.GetBiosSelections($parts[0]).Selections.Split(',')
}
} | Out-GridView

结果类似如下:

CurrentSetting                      Status                                Active AvailableSettings
--------------                      ------                                ------ -----------------
WakeOnLAN                           ACOnly                                  True {Disable, ACOnly, ACandBattery,...
WakeOnLANDock                       Enable                                  True {Disable, Enable}
EthernetLANOptionROM                Enable                                  True {Disable, Enable}
IPv4NetworkStack                    Enable                                  True {Disable, Enable}
IPv6NetworkStack                    Enable                                  True {Disable, Enable}
UefiPxeBootPriority                 IPv4First                               True {IPv6First, IPv4First}
WiGigWake                           Disable                                 True {Disable, Enable}
WirelessAutoDisconnection           Disable                                 True {Disable, Enable}
MACAddressPassThrough               Disable                                 True {Disable, Enable}
USBBIOSSupport                      Disable                                 True {Disable, Enable}
AlwaysOnUSB                         Enable                                  True {Disable, Enable}
TrackPoint                          Automatic                               True {Disable, Automatic}
TouchPad                            Automatic                               True {Disable, Automatic}
FnCtrlKeySwap                       Disable                                 True {Disable, Enable}
FnSticky                            Disable                                 True {Disable, Enable}
FnKeyAsPrimary                      Disable                                 True {Disable, Enable}
BootDisplayDevice                   LCD                                     True {LCD, USBTypeC, HDMI, DockDisplay}
SharedDisplayPriority               DockDisplay                             True {HDMI, DockDisplay}
TotalGraphicsMemory                 256MB                                   True {256MB, 512MB}
BootTimeExtension                   Disable                                 True {Disable, 1, 2, 3...}
SpeedStep                           Enable                                  True {Disable, Enable}
AdaptiveThermalManagementAC         MaximizePerformance                     True {MaximizePerformance, Balanced}
AdaptiveThermalManagementBattery    Balanced                                True {MaximizePerformance, Balanced}
CPUPowerManagement                  Automatic                               True {Disable, Automatic}
OnByAcAttach                        Disable                                 True {Disable, Enable}
PasswordBeep                        Disable                                 True {Disable, Enable}
KeyboardBeep                        Enable                                  True {Disable, Enable}
AMTControl                          Enable                                  True {Disable, Enable, Disable}
USBKeyProvisioning                  Disable                                 True {Disable, Enable}
WakeByThunderbolt                   Enable                                  True {Disable, Enable}
ThunderboltSecurityLevel            UserAuthorization                       True {NoSecurity, UserAuthorization,...
PreBootForThunderboltDevice         Disable                                 True {Disable, Enable, Pre-BootACL}
PreBootForThunderboltUSBDevice      Disable                                 True {Disable, Enable}
LockBIOSSetting                     Disable                                 True {Disable, Enable}
MinimumPasswordLength               Disable                                 True {Disable, 4, 5, 6...}
BIOSPasswordAtUnattendedBoot        Enable                                  True {Disable, Enable}
BIOSPasswordAtReboot                Disable                                 True {Disable, Enable}
BIOSPasswordAtBootDeviceList        Disable                                 True {Disable, Enable}
PasswordCountExceededError          Enable                                  True {Disable, Enable}
FingerprintPredesktopAuthentication Enable                                  True {Disable, Enable}
FingerprintReaderPriority           External                                True {External, InternalOnly}
FingerprintSecurityMode             Normal                                  True {Normal, High}
FingerprintPasswordAuthentication   Enable                                  True {Disable, Enable}
SecurityChip                        Enable                                  True {Active, Inactive, Disable, Ena...
TXTFeature                          Disable                                 True {Disable, Enable}
PhysicalPresenceForTpmProvision     Disable                                 True {Disable, Enable}
PhysicalPresenceForTpmClear         Enable                                  True {Disable, Enable}
BIOSUpdateByEndUsers                Enable                                  True {Disable, Enable}
SecureRollBackPrevention            Enable                                  True {Disable, Enable}
WindowsUEFIFirmwareUpdate           Enable                                  True {Disable, Enable}
DataExecutionPrevention             Enable                                  True {Disable, Enable}
VirtualizationTechnology            Enable                                  True {Disable, Enable}
VTdFeature                          Enable                                  True {Disable, Enable}
EthernetLANAccess                   Enable                                  True {Disable, Enable}
WirelessLANAccess                   Enable                                  True {Disable, Enable}
WirelessWANAccess                   Enable                                  True {Disable, Enable}
BluetoothAccess                     Enable                                  True {Disable, Enable}
USBPortAccess                       Enable                                  True {Disable, Enable}
MemoryCardSlotAccess                Enable                                  True {Disable, Enable}
SmartCardSlotAccess                 Enable                                  True {Disable, Enable}
IntegratedCameraAccess              Enable                                  True {Disable, Enable}
MicrophoneAccess                    Enable                                  True {Disable, Enable}
FingerprintReaderAccess             Enable                                  True {Disable, Enable}
ThunderboltAccess                   Enable                                  True {Disable, Enable}
NfcAccess                           Enable                                  True {Disable, Enable}
WiGig                               Enable                                  True {Disable, Enable}
BottomCoverTamperDetected           Disable                                 True {Disable, Enable}
InternalStorageTamper               Disable                                 True {Disable, Enable}
ComputraceModuleActivation          Enable                                  True {Disable, Enable, Disable}
SecureBoot                          Disable                                 True {Disable, Enable}
SGXControl                          SoftwareControl                         True {Disable, Enable, SoftwareControl}
DeviceGuard                         Disable                                 True {Disable, Enable}
BootMode                            Quick                                   True {Quick, Diagnostics}
StartupOptionKeys                   Enable                                  True {Disable, Enable}
BootDeviceListF12Option             Enable                                  True {Disable, Enable}
BootOrder                           USBCD:USBFDD:NVMe0:HDD0:USBHDD:PCILAN   True {HDD0, HDD1, HDD2, HDD3...}
NetworkBoot                         USBFDD                                  True {HDD0, HDD1, HDD2, HDD3...}
BootOrderLock                       Disable                                 True {Disable, Enable}

PowerShell 技能连载 - 管理 Lenovo BIOS 设置(第 1 部分)

不幸的是,没有一个标准的方法来管理计算机厂商的 BIOS 设置。每个厂商使用专有的方法。对于 Lenovo 电脑,您可以使用 WMI 来存取和转储 BIOS 设置:

1
2
3
4
5
6
7
8
9
10
Get-WmiObject -Class Lenovo_BiosSetting -Namespace root\wmi |
Where-Object CurrentSetting |
ForEach-Object {
$parts = $_.CurrentSetting.Split(',')
[PSCustomObject]@{
Setting = $parts[0]
Status = $parts[1]
Active = $_.Active
}
}

结果看起来类似这样:

Setting                             Status                                Active
-------                             ------                                ------
WakeOnLAN                           ACOnly                                  True
WakeOnLANDock                       Enable                                  True
EthernetLANOptionROM                Enable                                  True
IPv4NetworkStack                    Enable                                  True
IPv6NetworkStack                    Enable                                  True
UefiPxeBootPriority                 IPv4First                               True
WiGigWake                           Disable                                 True
WirelessAutoDisconnection           Disable                                 True
MACAddressPassThrough               Disable                                 True
USBBIOSSupport                      Disable                                 True
AlwaysOnUSB                         Enable                                  True
TrackPoint                          Automatic                               True
TouchPad                            Automatic                               True
FnCtrlKeySwap                       Disable                                 True
FnSticky                            Disable                                 True
FnKeyAsPrimary                      Disable                                 True
BootDisplayDevice                   LCD                                     True
SharedDisplayPriority               DockDisplay                             True
TotalGraphicsMemory                 256MB                                   True
BootTimeExtension                   Disable                                 True
SpeedStep                           Enable                                  True
AdaptiveThermalManagementAC         MaximizePerformance                     True
AdaptiveThermalManagementBattery    Balanced                                True
CPUPowerManagement                  Automatic                               True
OnByAcAttach                        Disable                                 True
PasswordBeep                        Disable                                 True
KeyboardBeep                        Enable                                  True
AMTControl                          Enable                                  True
USBKeyProvisioning                  Disable                                 True
WakeByThunderbolt                   Enable                                  True
ThunderboltSecurityLevel            UserAuthorization                       True
PreBootForThunderboltDevice         Disable                                 True
PreBootForThunderboltUSBDevice      Disable                                 True
LockBIOSSetting                     Disable                                 True
MinimumPasswordLength               Disable                                 True
BIOSPasswordAtUnattendedBoot        Enable                                  True
BIOSPasswordAtReboot                Disable                                 True
BIOSPasswordAtBootDeviceList        Disable                                 True
PasswordCountExceededError          Enable                                  True
FingerprintPredesktopAuthentication Enable                                  True
FingerprintReaderPriority           External                                True
FingerprintSecurityMode             Normal                                  True
FingerprintPasswordAuthentication   Enable                                  True
SecurityChip                        Enable                                  True
TXTFeature                          Disable                                 True
PhysicalPresenceForTpmProvision     Disable                                 True
PhysicalPresenceForTpmClear         Enable                                  True
BIOSUpdateByEndUsers                Enable                                  True
SecureRollBackPrevention            Enable                                  True
WindowsUEFIFirmwareUpdate           Enable                                  True
DataExecutionPrevention             Enable                                  True
VirtualizationTechnology            Enable                                  True
VTdFeature                          Enable                                  True
EthernetLANAccess                   Enable                                  True
WirelessLANAccess                   Enable                                  True
WirelessWANAccess                   Enable                                  True
BluetoothAccess                     Enable                                  True
USBPortAccess                       Enable                                  True
MemoryCardSlotAccess                Enable                                  True
SmartCardSlotAccess                 Enable                                  True
IntegratedCameraAccess              Enable                                  True
MicrophoneAccess                    Enable                                  True
FingerprintReaderAccess             Enable                                  True
ThunderboltAccess                   Enable                                  True
NfcAccess                           Enable                                  True
WiGig                               Enable                                  True
BottomCoverTamperDetected           Disable                                 True
InternalStorageTamper               Disable                                 True
ComputraceModuleActivation          Enable                                  True
SecureBoot                          Disable                                 True
SGXControl                          SoftwareControl                         True
DeviceGuard                         Disable                                 True
BootMode                            Quick                                   True
StartupOptionKeys                   Enable                                  True
BootDeviceListF12Option             Enable                                  True
BootOrder                           USBCD:USBFDD:NVMe0:HDD0:USBHDD:PCILAN   True
NetworkBoot                         USBFDD                                  True
BootOrderLock                       Disable                                 True

PowerShell 技能连载 - 探索 PowerShell 模块

大多数 cmdlet 和函数是 PowerShell 模块的一部分。如果您希望探索这些命令究竟是从哪儿来的,以下是一个简单的实践。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# replace the command name with any PowerShell command name
# you'd like to explore
$Name = "Get-Printer"
$ModuleName = (Get-Command -Name $Name -CommandType Function, Cmdlet).Source

if ('' -eq $ModuleName)
{
Write-Warning "$Name was defined in memory, no module available."
return
}

Write-Warning "$Name resides in $ModuleName module"

$module = Get-Module -Name $ModuleName -ListAvailable
explorer $module.ModuleBase

只需要将 $name 改为您希望探索的任何 PowerShell cmdlet 名称即可。如果该命令存在于一个 PowerShell 模块中,该模块将打开一个 Windows 资源管理器,您可以在其中检查它的内容。

PowerShell 技能连载 - 锁定工作站

如果您希望在 PowerShell 中锁定当前工作站,您可以利用 PowerShell 可以运行可执行程序的特性。以下是一个使用 rundll32.exe 来调用一个 Windows 内部函数来锁定工作站的快速函数:

1
2
3
4
function Lock-Workstation
{
rundll32.exe user32.dll,LockWorkStation
}

PowerShell 技能连载 - 检测 WinPE

PowerShell 可以在 WinPE 环境中运行。如果您希望检测 PowerShell 脚本是否运行在 WinPE 员警中,您只需要检查某个注册表键是否存在:

1
2
3
4
function Test-WinPE
{
return Test-Path -Path Registry::HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlset\Control\MiniNT
}

如果您在 WinPE 环境中运行,这个函数返回 $true

PowerShell 技能连载 - 从 ZIP 压缩包中解压指定的文件

PowerShell 提供了新的 cmdlet,例如 Extract-Archive,可以从一个 ZIP 文件中解压(所有的)文件。然而,只能解压整个压缩包。

如果您希望解压独立的文件,您可以使用 .NET 方法。以下是一个实现的示例:

  • 它打开一个 ZIP 文件来读取内容
  • 它查找该 ZIP 文件中所有符合指定文件扩展名的文件
  • 它只解压这些文件到您指定的输出目录

代码中的注释解释了代码在做什么。只需要确保您调整了初始变量并且制定了一个存在的 ZIP 文件,以及一个在 ZIP 文件中存在的文件扩展名:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#requires -Version 5.0

# change $Path to a ZIP file that exists on your system!
$Path = "$Home\Desktop\Test.zip"

# change extension filter to a file extension that exists
# inside your ZIP file
$Filter = '*.wav'

# change output path to a folder where you want the extracted
# files to appear
$OutPath = 'C:\ZIPFiles'

# ensure the output folder exists
$exists = Test-Path -Path $OutPath
if ($exists -eq $false)
{
$null = New-Item -Path $OutPath -ItemType Directory -Force
}

# load ZIP methods
Add-Type -AssemblyName System.IO.Compression.FileSystem

# open ZIP archive for reading
$zip = [System.IO.Compression.ZipFile]::OpenRead($Path)

# find all files in ZIP that match the filter (i.e. file extension)
$zip.Entries |
Where-Object { $_.FullName -like $Filter } |
ForEach-Object {
# extract the selected items from the ZIP archive
# and copy them to the out folder
$FileName = $_.Name
[System.IO.Compression.ZipFileExtensions]::ExtractToFile($_, "$OutPath\$FileName", $true)
}

# close ZIP file
$zip.Dispose()

# open out folder
explorer $OutPath

PowerShell 技能连载 - 提取 ZIP 压缩包信息

PowerShell 提供了新的 cmdlet,例如 Extract-Archive,可以从一个 ZIP 文件中解压(所有的)文件。然而,并没有方法列出一个 ZIP 文件中的内容。

要实现这个目的,您可以使用 Extract-Archive 中使用的 .NET 库。这段代码将输入一个 ZIP 文件并提取它的内容(请确保您将 ZIP 的路径改为一个实际存在的路径):

1
2
3
4
5
6
7
8
9
# adjust this to a valid path to a ZIP file
$Path = "$Home\Desktop\Test.zip"

# load the ZIP types
Add-Type -AssemblyName System.IO.Compression.FileSystem
$zip = [System.IO.Compression.ZipFile]::OpenRead($Path)
$zip.Entries

$zip.Dispose()