PowerShell教程 - 编程结构(Program Struct)- 第三部分

news/2024/5/17 16:59:35/文章来源:https://www.cnblogs.com/cqpanda/p/16589955.html

更新记录
转载请注明出处。
2022年8月21日 发布。
2022年8月18日 从笔记迁移到博客。

预定义变量

预定义的布尔值

$True
$False

预定义变量

预定义变量					描述(Description)
$^								表示当前会话的使用过的最后一条命名的最前部分
$$								表示当前会话的使用过的最后一条命名的最后部分
$?             表示最后一条命令的执行状态
返回true 表示执行成功,返回false表示执行失败
$_					等同于$PSItem包含管道对象中的当前对象可以在管道中的每个对象或选定对象执行操作的命令中使用此变量
$ARGS	Represents an array of the undeclared parameters and/or parameter values that are passed to a function, script, or script block.
$CONSOLEFILENAME	Represents the path of the console file (.psc1) that was most recently used in the session.
$ERROR	Represents an array of error objects that represent the most recent errors.
$EVENT	Represents a PSEventArgs object that represents the event that is being processed.
$EVENTARGS	Represents an object that represents the first event argument that derives from EventArgs of the event that is being processed.
$EVENTSUBSCRIBER	Represents a PSEventSubscriber object that represents the event subscriber of the event that is being processed.
$EXECUTIONCONTEXT	Represents an EngineIntrinsics object that represents the execution context of the PowerShell host.
$FALSE	Represents FALSE. You can use this variable to represent FALSE in commands and scripts instead of using the string "false".
$FOREACH	Represents the enumerator (not the resulting values) of a ForEach loop. You can use the properties and methods of enumerators on the value of the $ForEach variable.
$HOME	Represents the full path of the user's home directory.
$HOST	Represents an object that represents the current host application for PowerShell.
$INPUT	Represents an enumerator that enumerates all input that is passed to a function.
$LASTEXITCODE	Represents the exit code of the last Windows-based program that was run.
$MATCHES	The $Matches variable works with the -match and -notmatch operators.
$MYINVOCATION	$MyInvocation is populated only for scripts, function, and script blocks. PSScriptRoot and PSCommandPath properties of the $MyInvocation automatic variable contain information about the invoker or calling script, not the current script.
$NESTEDPROMPTLEVEL	Represents the current prompt level.
$NULL	$null is an automatic variable that contains a NULL or empty value. You can use this variable to represent an absent or undefined value in commands and scripts.
$PID	Represents the process identifier (PID) of the process that is hosting the current PowerShell session.
$PROFILE	Represents the full path of the PowerShell profile for the current user and the current host application.
$PSCMDLET	Represents an object that represents the cmdlet or advanced function that is being run.
$PSCOMMANDPATH	Represents the full path and file name of the script that is being run.
$PSCULTURE	Represents the name of the culture currently in use in the operating system.
$PSDEBUGCONTEXT	While debugging, this variable contains information about the debugging environment. Otherwise, it contains a NULL value.
$PSHOME	Represents the full path of the installation directory for PowerShell.
$PSITEM	Same as $_. Contains the current object in the pipeline object.
$PSSCRIPTROOT	Represents the directory from which a script is being run.
$PSSENDERINFO	Represents information about the user who started the PSSession, including the user identity and the time zone of the originating computer.
$PSUICULTURE	Represents the name of the user interface (UI) culture that is currently in use in the operating system.
$PSVERSIONTABLE	Represents a read-only hash table that displays details about the version of PowerShell that is running in the current session.
$SENDER	Represents the object that generated this event.
$SHELLID	Represents the identifier of the current shell.
$STACKTRACE	Represents a stack trace for the most recent error.
$THIS	In a script block that defines a script property or script method, the $This variable refers to the object that is being extended.

环境变量管理

获得环境变量

获得全部环境变量

Get-ChildItem env:

或者

dir env:

获得单个环境变量

变量语法形式格式:

$env:环境变量名称

使用Get-Item形式:

Get-Item env:temp

获得TEMP变量

$env:TEMP

获得APPDATA变量

$env:APPDATA

获得HOME目录

$env:HOMEPATH

获得处理器个数NUMBER_OF_PROCESSORS
注意:这是处理器的线程数

$env:NUMBER_OF_PROCESSORS

获得处理器的架构

$env:PROCESSOR_ARCHITECTURE

获得OS类型

$env:OS

获得Path信息

$env:Path

获得Windows目录

$env:windir

设置环境变量

$env:ASPNETCORE_ENVIRONMENT="Production"

cmd设置环境变量

set ASPNETCORE_ENVIRONMENT=Production

输入输出

获得用户输入

Read-Host

实例:

$userInput = Read-Host "请输入你的长度"

输出内容到标准输出

image

Write-Host

实例:
输出文本

Write-Host "panda"

设置前景色和背景色

Write-Host "COLORFUL!" -Fore Yellow -Back Magenta

输出警告信息

Write-Warning

实例:
输出警告信息

Write-Warning "cmdlet is used to write warning messages" 

输出警告信息

Write-Warning "Test Warning" 

执行应用文件默认行为

perform a default action on specified item

Invoke-Item

实例:

Invoke-Item "D:\test.txt"

执行字符串表达式

Invoke-Expression

实例:

$Command = 'Get-Process'
Invoke-Expression $Command

测试命令执行的时间

Measure-Command

实例:

Measure-Command { Get-EventLog "Windows PowerShell" }

运算符(Operators)

算术运算符(Arithmetic Operators)

说明
Arithmetic operators are used to perform numeric calculations
Arithmetic operator also be used with strings, arrays, and hash tables
注意:加号+除了进行算数运算,还用于连接字符串
注意:加号+还可以用于为数组添加元素
注意:The division and remainder operators perform mathematical operations only
注意:求余运算和C#一样,结果的符号取决于第一个运算数

算数运算符

+ 		    Addition					
- 		    Subtraction				
* 		    Multiplication				
/ 		    Division					
% 		    Remainder				
-shl		Shift left					
-shr		Shift right	

Addition Operator实例:
简单算数运算

2.71828 + 3.14159          #5.85987

连接字符串

'www.' + 'Panda666.com'    #www.Panda666.com

连接字符串和数值(数值如果在前面会报错,需要进行类型转换)

'Hello Panda ' + 666       # Hello Panda 666
[string]666 + 'Panda'      #666Panda

为数组添加元素

@(666, 888) + 999 + 'Panda' + $True `

连接两个数组

@(1, 2) + @(3, 4)
(1, 2) + (3, 4)
1, 2 + 3, 4

连接HashTable(注意:如果Key是相同的,会报错)

@{Name = 'Panda'} + @{Code = 666} 

Multiplication Operator实例:
简单乘法:

2.5 * 2

字符串重复连接

'Panda666' * 3

用于重复数组的元素

@('one', 'two') * 2
('one', 'two') * 2
'one', 'two' * 2

Division operator实例:
简单除法:

20 / 5

Remainder operator实例:

3 % 2

链式使用

1..100 | Where-Object { $_ % 5 -eq 0 } | ForEach-Object {Write-Host $_}

Shift left and shift right operators实例:
简单左移

78 -shl 1

可以指定数据类型的大小

([Byte]255) -shl 1
([Int16]255) -shl 1

有符号数如果左移超过范围会导致循环

([SByte]64) -shl 1   #-128

比较运算符(Comparison Operators)

-eq and -ne                 	Equal to and not equal to
-gt and -ge                 	Greater than and greater than or equal to
-lt and -le                 	Less than and less than or equal to
-like and -notlike          	Like and not like
-contains and -notcontains  	Contains and not contains
-in and -notin              	In and not in

注意,当比较文本字符串时默认会忽略大小写,大写字母与小写字母等价
也可以显式的声明为不区分大小写,只需要在运算符前加上i即可

-ieq,-ine,-igt,-ilt,-ige,-ile

对于字符串的比较,如果需要区分大小写,在运算符前,加上c即可

-ceq,-cne,-cgt,-clt,-cge,-cle

实例:
相等比较

"Panda666" -eq "Panda666"   #True
"panda666" -eq "Panda666"   #True
"panda666" -ceq "Panda666"  #False

大小比较

(5 -gt 10) -or (10 -lt 100) #True

检测包含

1, 2 -contains 2 # Returns true
1, 2, 3 -contains 4 # Returns false

检测存在

1 -in 1, 2, 3 # Returns true
4 -in 1, 2, 3 # Returns false

比较运算符与数组混用(Comparison operators and arrays)
默认情况下比较运算符返回true或false
如果与数组混用,则返回满足条件的元素

1, $null -ne $null 		# Returns 1
1, 2, 3, 4 -ge 3 		# Returns 3, 4
'one', 'two', 'three' -like '*e*' # Returns one and three 

这也会造成一些问题,比如:检测数组是否为null

$array = 1, 2, $null, $null
if ($array -eq $null) { Write-Host 'No values in array' } 

以上的比较将会成功,但是数组又是有元素的
可以通过以下方式来解决

$array = 1, 2, $null, $null
if ($null -eq $array) { Write-Host 'Variable not set' }

逻辑运算符(Logical Operators)

-and			与运算
-or			    或运算
-not			非运算
-xor			异或

提示:-not也可以使用!,是等价的

实例:

(5 -gt 10) -or (10 -lt 100) #True
(5 -gt 10) -or $True         #True
-not $false
-not (Test-Path X:\)
-not ($true -and $false)
!($true -and $false)

赋值运算符(Assignment Operators)

赋值运算符:

=		Assign
+=		Add and assign
-=		Subtract and assign
*=		Multiply and assign
/=		Divide and assign
%=		Modulus and assign

实例:
数值运算

$num = 666;
$num +=222;

字符串连接

$string = 'panda'
$string += '666' 

混合字符串和数值类型进行运算

$var = 'Panda'
$var += 666;

如果是数值类型在前面,记得转为字符串再进行运算

[string]$var = 666  #将数值转为字符串
$var += 'Panda';

数组添加元素

$array = 666,888
$array += 888

数组合并数组

$array = 666,888
$array += 888,666

合并HashTable

$hashtable = @{Name = 'Panda'}
$hashtable += @{Code = 666} 

重复字符串

$string = 'one'
$string *= '2' 

重复数组

$arr = 1, 2
$arr *= 2

正则表达式运算符(Regular expression-based operators)

-match          	    Match
-notmatch       	    Not match
-replace        		Replace
-split          		Split

提示:还有区分大小写的-creplace命令、-csplit命令

实例:
匹配字符串

'The cow jumped over the moon' -match 'cow' # Returns true
'The cow' -match 'The +cow' # Returns true

匹配字符串中的数字

'1234567689' -match '[0-4]*'

匹配数组的元素

"one", "two", "three" -match 'e'

替换

'abababab' -replace 'a', 'c'

替换为空,等价于移除

'abababab' -replace 'a'

分割

'a1b2c3d4' -split '[0-9]'

位运算符(Bitwise operators)

-band   	Binary and
-bor    	Binary or
-bxor   	Binary exclusive or
-bnot   	Binary not

实例:
按位与

11 -band 6

按位或

11 -bor 12

按位异或

6 -bxor 13
512 -bxor 2 		# Result is 514 (Disabled, 2 is set)
514 -bxor 2 		# Result is 512 (Enabled, 2 is not set)

按位非

-bnot 122

重定向运算符(Redirection operators)

具体查看管道笔记

实例:
重定向到文件中

Get-Process -Id $pid > process.txt

警告输出流重定向到文件

function Test-Redirect{Write-Warning "Warning $i"
}
Test-Redirect 3> 'warnings.txt' # Overwrite
$i++
Test-Redirect 3>> 'warnings.txt' # Append

类型运算符(Type operators)

说明
Type operators are designed to work with .NET types
These operators may be used to convert an object of one type into another, or to test whether or not an object is of a given type

类型运算符(Type operators):
-as As运算符,将一种已存在的对象转换为新的对象类型,从而产生一个新的对象
-is Is运算符,判断某个对象是否为特定类型,如果是,则返回True,否则为False
-isnot Is not运算符,-is运算的反向

-as实例:
简单类型转换

"1" -as [Int32]

转为System.Reflection.MemberInfo类型

'String' -as [Type]

运算结果转为指定类型

1000 / 3 –AS [INT]
$panda = 1000 / 3 –AS [INT];

导入类型(程序集)

if (-not ('System.Web.HttpUtility' -as [Type])) {Write-Host 'Adding assembly' -ForegroundColor GreenAdd-Type -Assembly System.Web
}

-is、-isnot实例:
检测是否指定类型

'string' -is [String]
123.45 -IS [INT]                #False
(Get-Date) -IS [DateTime]       #True

检测是否[Int32]类型

1 -is [Int32]

检测是否类型

[String] -is [Type]

检测是否不是[string]类型

123 -isnot [String]

其他运算符(Other operators)

&				Call,用于执行命令,执行代码块
,				Comma,逗号运算符,用于分隔数组元素等
-f 				Format,用于格式化字符串,和C#基本相同
++ and --		Increment and decrement
-join 			Join

&实例:
执行cmd命令

$command = 'ipconfig'
& $command

执行Powershell命令:

$command = 'Get-Location'
& $command

执行代码块:

$scriptBlock = { Write-Host 'Panda666.com' }
& $scriptBlock

还支持指定参数

& 'ipconfig' '/displaydns'

-f实例:
简单格式化

'1: {0}, 2: {1}, 3: {2}'  -f  1, 2, 3

使用格式化字符

'1: {0:F}, 2: {1:C2}, 3: {2:F3}'  -f  1, 2, 3
'The pass mark is {0:P}' -f 0.8
'244 in Hexadecimal is {0:X2}' -f 244

-f会转换{}符号,如果需要保留{}可以使用{{}}即可

'The value in {{0}} is {0}' -f 1

++ and –实例:
常用于循环变量中

for ($i = 0; $i -le 15; $i++) {Write-Host $i -ForegroundColor $i
}

-join实例:
将数组转化为分隔列表的字符串

$Array = "one","two","three","four","five"
$Array -Join "|"

分割后再连接起来

"a,b,c,d" -split ',' -join "`t"

还可以使用这种格式

-join ('h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd')

..(范围运算符)

1..10会返回1到10的十个对象

1..10
?(问号)是Where-Object Cmdlet的别名
%(百分号)是ForEach-Object Cmdlet的别名
>(右尖括号)类似Out-File Cmdlet的别名
&(与符号)是PowerShell中的一个调用运算符,使得PowerShell可以将某
些字符识别为命令,并运行这些命令。例如,$a="Dir"命令将“Dir”赋给了变
量$a,然后&$a就会执行Dir命令。
;(分号)一般用作分隔PowerShell中同一行的两个命令:Dir;Get-Process。
这个命令会先执行Dir命令,之后执行Get-Process命令。它们的执行结果会发送
给一个管道,但是Dir命令的执行结果并不会通过管道发送给Get- Process命令

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.luyixian.cn/news_show_379881.aspx

如若内容造成侵权/违法违规/事实不符,请联系dt猫网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

压测工具 Locust

Locust是一款易于使用的分布式负载测试工具,完全基于事件,即一个locust节点也可以在一个进程中支持数千并发用户,不使用回调,通过gevent使用轻量级过程(即在自己的进程内运行)一、认识Locust 定义 Locust是一款易于使用的分布式负载测试工具,完全基于事件,即一个locust…

#{}和${}的区别是什么

#{}和${}的区别是什么 动态 sql 是 MyBatis 的主要特性之一,在 mapper 中定义的参数传到 xml 中之后,在查询之前 MyBatis 会对其进行动态解析。MyBatis 为我们提供了两种支持动态 sql 的语法:#{} 以及 ${}。 区别 1)#{}是预编译处理,$ {}是字符串替换。 2)MyBatis在处理#…

Mybatis组件介绍

核心组件 SqlSessionFactoryBuilder SqlSessionFactoryBuilder的作用就是通过XML或者Java代码来建造一个工厂(SqlSessionFactory),并且可以通过它建造多个这样的工厂。一旦完成建造工厂的任务,我们就应该废弃它,回收空间。所以它的生命周期只存在方法局部,完成工厂的建造即…

JAVA入门2022年8月19日

第一节 1.注释是什么写在程序中对程序进行解释说明的文字。 2.java中书写注释的方法有几种,各自有什么不同// 单行注释/* */ 多行注释/** */ 文档注释 3.注释有什么特点不进行编译,不影响程序的执行 4.注释的快捷键是怎么样的 第二节1.字面…

vue的生命周期

一、Vue 的生命周期 一、Vue 的生命周期流程图二、Vue 生命周期的具体    生命周期 描述beforeCreate 组件实例被创建之初created 组件实例已经完成创建beforeMount 组件挂载之前mounted 组件挂载到实例上去之后beforeUpdate 组件数据发生变化,更新之前updated 组件数据更新…

spring源码学习笔记1——解析xml生成BeanDefinition的过程解析

spring源码学习笔记1——解析xml生成BeanDefinition的过程解析 一丶Spring解析Xml生成BeanDefinition的流程 1.指定xml路径 解析xml首先需要知道xml的位置,如下我们构造了ApplicationContext ApplicationContext context =new ClassPathXmlApplicationContext("bean.xml&…

IOC

介绍 什么是SpringIOC,就是把每一个bean(实体类)与bean(实体类)之间的关系交给第三方容器进行管理。关键类BeanFactory IOC的顶层容器,描述了IOC的规范。 BeanFactory是一个接口,是Spring中工厂的顶层规范,IOC的核心接口。 定义了getBean()、containsBean()等管理Bean的通用…

JUC进阶

JUC进阶 wait和sleep的区别sleep是Thread的静态方法,wait是Object方法sleep不会释放锁,它也不需要占用锁,wait会释放锁但调用它的前提是当前线程占有锁wait必须在同步代码块中Lock锁public class LockTest { public static void main(String[] args) { Ticket t…

Spring 03: 基于xml的构造方法注入

构造方法注入具体有3种注入方式:通过构造方法的 a.参数名称注入 b.参数下标注入 c.默认参数顺序注入参数名称注入School实体类package com.example.pojo03;public class School {private String name;private String address;@Overridepublic String toString() {return &…

Vmware 安装CentOS 7

Vmware 安装CentOS 7 创建虚拟机 1、新建虚拟机,选择自定义(高级),下一步。其他默认下一步。选择操作系统Linux,CentOS 7 64位,下一步。输入主机名称,虚拟机存储位置。 2、输入内核数量3、输入内存大小,下一步,其他默认下一步。4、指定磁盘大小,下一步5、自定义硬件,…

深度学习基础课:课程介绍

大家好~我开设了“深度学习基础班”的线上课程,带领同学从0开始学习全连接和卷积神经网络,进行数学推导,并且实现可以运行的Demo程序 本文为第一节课:课程介绍的复盘文章深度学习基础课:课程介绍 大家好~我开设了“深度学习基础班”的线上课程,带领同学从0开始学习全连接…

一台服务器​最大并发 TCP 连接数多少

一台服务器​最大并发 TCP 连接数多少 入门小站 入门小站 2022-07-06 22:10 发表于湖北收录于合集#Linux485个 #tcp4个首先,问题中描述的65535个连接指的是客户端连接数的限制。在tcp应用中,server事先在某个固定端口监听,client主动发起连接,经过三路握手后建立tcp连接。那…

js的原型

prototype 概述:所有的函数都拥有一个属性 这个属性称为prototype 他是一个对象空间(里面就可以存放对应的数据)他被称为显式原型从上述代码 大家可以看到对应的构造函数的prototype和对应的实例对象的 __proto__ 是相等,那么也就证明了对应俩个内容其实是一个对象。那么我…

Condition介绍

Condition Condition是一种多线程通信工具,表示多线程下参与数据竞争的线程的一种状态,主要负责多线程环境下对线程的挂起和唤醒工作。 方法 // ========== 阻塞 ========== // 造成当前线程在接到信号或被中断之前一直处于等待状态。 void await() throws InterruptedExcept…

解决goland在mac m1下无法调试问题

背景 新电脑mac m1 goland调试抛出异常 异常信息 第一次异常信息 could not launch process: can not run under Rosetta, check that the installed build of Go is right for your CPU architecture 原因是goland版本安装错了. 下载地址:https://www.jetbrains.com/zh-cn/go…

排序(上)

目录冒泡排序(Bubble Sort)插入排序(Insertion Sort)选择排序(Selection Sort)冒泡排序和插入排序的比较 最经典的、最常用的有:冒泡排序、插入排序、选择排序、归并排序、快速排序、计数排序、基数排序、桶排序 冒泡排序(Bubble Sort) 冒泡排序只会操作相邻的两个数据…

Codeforces Round #815 (Div. 2) 题解

Codeforces Round #815 (Div. 2) 全场题解CF1720A. Burenka Plays with Fractions给出两个分数 $ \dfrac{a}{b}$ 和 \(\dfrac{c}{d}\) ,你每次操作能够选择其中一个分数的分子或分母,将其乘上任意一个整数(当然不能对分母乘 \(0\))。要求求出能够使两个分数相等的最小操作次…

2022 牛客多校 Extra 第九场部分题解

2022 牛客多校第九场 & Extra 部分题解 前段时间沉迷生活大爆炸 & 原神 & vtb & galgame & 番无法自拔,因此咕到现在。。。 Cmostp 挺妙的题。本以为有一只 log 的做法。 覆盖后的颜色变换不多,可以用 set+树剖或者阉割版的lct+树状数组,我写了后者,把…

【小迪安全】04:基础入门-web源码扩展

(XYCMS搬家公司建站系统) 查找数据库文件路径: 发现后缀名为mdb文件——为asp网站特有的 打开mdb文件找到 admin_user数据库可以找到用户名和密码

解决无法访问GitHub

一、获取IP地址可以直接通过网站 查询域名 github.com 的IP地址,无论哪种方法一定得是通过自己本机查到的IP,网上别人查到的IP你不一定有用。https://www.ipaddress.com/二、修改hosts文件 Windows hosts文件路径: C:\Windows\System32\drivers\etc 在对应目录找到hosts文件,…