PowerShell学习笔记

-目录-

常用cmdlet

常用命令

常识

文件

#添加内容到文件 add-content filename content 
add-content test.txt "hello"
#替换文件内容 set-content filename content
set-content test.txt "hi"
#查看文件内容 get-content filename
get-content test.txt
#清空文件内容 clear-content filename
clear-content test.txt

#拷贝文件 copy-item src des
copy-item test.txt test2.txt
#移动文件 move-item src des
move-item test.txt des

#新建文件 new-item filename
new-item test.txt
#删除文件 remove-item filename
remove-item test.txt

#重命名 rename-item oldname newname
rename-item test.txt test2.txt

位置

#显示当前位置 pwd
get-location
#切换当前位置 cd
set-location

其他常用

#命令行输出重定向 out-file filename 等同于 >
#若不指定append则覆写
get-childItem > test.txt
#测试文件是否存在,可加日期限定等 test-path
test-path path
#打印对象 write-host object
write-host something
#排序,可以按照指定属性排序 sort-object
get-childitem | sort-object
#查找 where-object 条件
get-service | where-object {$_.Name -Match "^Wp.*"}     

变量

基本操作

#创建
$myvariable=1
#修改
$myvariable=2
#删除
$clear-variable myvariable

变量作用域

Powershell分为三种变量

自动变量列表

变量类型

和python一样是弱类型的,变量间类型可以互换

#创建数组
$arr=1,2,3,4
$arr2=1..10
$arr="aa","bb"
$arr=@()#空数组
#append数组
$arr += 11

#创建hash表
$myhash=@{1="ok";2="yes"}
#读取
$myhash.1

运算符

同大多数编程语言一样

特殊的是特殊运算符

$a="PowerShell";$b="*Shell" 
# 比较运算符是-eq -nq
$a -eq $b
# 匹配运算符-like+正则
$a -like $b
# 包含运算符-contains+集合
$c="PowerShell","sh"
$c -contains $a
#替换replace<input> <operator> <original> , <substitute>
$c -replace "sh","zsh"

流程控制

类似C语言

#遍历对象,管道传输
get-childitem  -Path 'D:' | foreach-object {write-host $_}
© 2019 - 2023 · YuYoung's Blog