一. 基本用法
1.定义变量
$variableName="name"
2.使用变量
Write-Output $variableName
3.if语句
if ($condition) {
#执行语句
} elseif ($anotherCondition) {
#执行语句
} else {
#执行语句
}
示例:
$number=10
if ($numver -gt 5) {
Write-Output "number is greater than 5"
} else {
Write-Output "number is 5 or less"
}
4.循环
for循环:
for ($i=0; $i -lt 5; $i++) {
Write-Output $i
}
foreach循环:
$array=1,2,3,4,5
foreach($item is $array)
{
Write-Output $item
}
while循环:
$count=0
While($counter -lt 5)
{
Write-Output $count
$count++
}
5.函数
定义函数:
function Get-Greeting {
param (
[string]$Name
)
"Hello, $Name"
}
调用函数:
Get-Greeting -Name "Alice"
6.文件操作
读取文件:
Get-Countent "path\to\file.txt"
写入文件:
"Hello, World" | Out-File "path\to\file.txt"
追加文件:
"Additional line" | Add-Content "path\to\file\txt"
7.错误处理:
try {
#执行代码
} catch {
#执行抛出了异常处理
} finally {
# 清理代码
}
8.模块
导入模块:
Import-Module ModuleName
获取模块:
Get-Module
查看模块命令:
Get-Command -Module ModuleName
9.脚本执行策略
查看执行策略:
Get-ExecutionPolicy
设置执行:
Set-ExecutePolicy RemoteSigned
10.示例脚本
#file example.ps1
$name="World"
Write-Output "Hello, $name!"
运行脚本:
.\example.ps1
11.Get-Item
Get-Item是PowerShell 中的一个 cmdlet,用于获取指定路径的一个项(即文件、目录或其他类型的对象)。它允许你从文件系统、注册表、环境变量等位置获取单个对象的信息。
作用
- 获取文件或目录:
Get-Item
可以用来获取文件系统中的文件或目录的对象。 - 获取注册表项:可以用来获取注册表中的项。
- 获取环境变量:可以用来获取环境变量的值。
- 获取其他类型的项:可以用来获取其他类型的项,如证书存储中的证书等。
语法:
Get-Item -Path <string>
示例:C:\example\file.txt
文件
获取文件详细信息:
Get-Item -Path "C:\example\file.txt"
获取目录详细信息:
Get-Item -Path "C:\example"
获取注册表项:
Get-Item -Path "HKLM:\Software\Microsoft"
获取环境变量:
Get-Item -Path "Env:PATH"
获取证书:
Get-Item -Path "Cert:\CurrentUser\My"