powershell基础

脚本以ps1后缀命名

参数使用$name命名
创建对象 $stu=@{ Name = "test";Age="12";sex="man" }
判断是否为数组 $test -is [array]
单行注释 #
多行注释 <# #>

条件判断
-eq :等于
-ne :不等于
-gt :大于
-ge :大于等于
-lt :小于
-le :小于等于
-contains :包含 如: $array -contains something
-notcontains :不包含

逻辑运算
!($a): 求反
-and :和
-or :或
-xor :异或
-not :逆

判断语句
if(){

}
else{

}

循环
1.
while($n -gt 0){
code
}

\(sum=0 for(\)i=1;\(i -le 100;\)i++)
{
\(sum+=\)i
}
$sum

foreach(\(file in dir c:\windows) { if(\)file.Length -gt 1mb)
{
$File.Name
}
}

Get-WmiObject Win32_Service | ForEach-Object {"Name:"+ \(_.DisplayName, ", Is ProcessId more than 100:" + (\)_.ProcessId -gt 100)}

函数
function Invoke-PortScan {
<#
.SYNOPSIS
简介

.DESCRIPTION
描述

.PARAMETER StartAddress
参数

.PARAMETER EndAddress
参数

.EXAMPLE
PS > Invoke-PortScan -StartAddress 192.168.0.1 -EndAddress 192.168.0.254
用例

>

code
}

异常处理
Try{ $connection.open() $success = $true }Catch{ $success = $false }

常用命令

Get-ChildItem 的别名为ls、dir

列出所有目录

Get-ChildItem -Attributes D

列出所有文件

Get-ChildItem -Attributes !D

如果需要只列出文件名,可以在上述命令的基础上添加-Name参数

Get-ChildItem -Attributes D -Name

for循环遍历所有的文件

foreach($i in Get-ChildItem -Attributes D -Name){
	echo $i	
}

获取脚本所在路径

$x = Split-Path -Parent $MyInvocation.MyCommand.Definition

判断路径是否存在

$TRUE_FALSE=(Test-Path $pslPath\publish)
if($TRUE_FALSE -eq "True"){
	 
}
else{
	 
}

压缩
Compress-Archive -Path D:\test -DestinationPath E:\test.zip

解压缩
Expand-Archive -Path D:\test.zip -DestinationPath F:\test

中文乱码
脚本文件使用UTF-8 BOM格式保存

如果遇到报错:【因为在此系统上禁止运行脚本】时可以使用下面的命令解决

set-executionpolicy remotesigned

[参考]
powershell基础
乱码问题解决方案

posted @ 2022-08-05 10:42  Hey,Coder!  阅读(31)  评论(0编辑  收藏  举报