---
tags: C:\Users\ccccchhhheeenng
---
# powershell basic
## 本文使用*PowerShell 7.4.0-preview.1*環境編寫
## 目錄
[TOC]
## 變數宣告
可以像python一樣 不須變數宣告
但想用特殊變數時須先宣告
```ps1
$name
nv
New-Variable(-Option(可設定變數型式))
```
:::spoiler Example 1
```ps1
PS C:\Users> nv YYOuO -Option ReadOnly -Value 87
PS C:\Users> Write-Output $YYOuO
87
PS C:\Users> $YYOuO=1234
WriteError: Cannot overwrite variable YYOuO because it is read-only or constant.
```
:::
:::spoiler Example 2
```ps1
PS C:\Users> $test=123
PS C:\Users> Write-Output $test
123
PS C:\Users> $str="Hello World"
PS C:\Users> Write-Output $str
Hello World
PS C:\Users>
```
:::
## 常用
### 指令說明
取得指令說明、指令別名、運用方式
```ps1
Get-Help [name]
```
:::spoiler Example
```ps1
PS C:\Users\ccccchhhheeenng> get-help cd
NAME
Set-Location
SYNTAX
Set-Location [[-Path] <string>] [-PassThru] [<CommonParameters>]
Set-Location -LiteralPath <string> [-PassThru] [<CommonParameters>]
Set-Location [-PassThru] [-StackName <string>] [<CommonParameters>]
ALIASES
sl
cd
chdir
REMARKS
Get-Help cannot find the Help files for this cmdlet on this computer. It is displaying only partial help.
-- To download and install Help files for the module that includes this cmdlet, use Update-Help.
-- To view the Help topic for this cmdlet online, type: "Get-Help Set-Location -Online" or
go to https://go.microsoft.com/fwlink/?LinkID=2097049.
```
:::
### 清理頁面
當頁面太亂時可以使用 個人是習慣動不動就cls一下
```ps1
Clear-Host
cls
clear
```
:::spoiler

```ps1
PS C:\>cls
```

:::
### 切換資料夾
切換路徑 當你要的檔案在其他地方時會很需要
```ps1
Set-Location
sl
cd
chdir
```
:::spoiler Example
```ps1
PS C:\Windows\System32> cd ..
PS C:\Windows> sl ..
```
:::
### 列出當前路徑下的物件
可以將當前路徑的檔案、資料夾列出來
```ps1
ls
dir
gci
Get-ChildItem
```
:::spoiler Example
```ps1
PS C:\> ls
Directory: C:\
Mode LastWriteTime Length Name
---- ------------- ------ ----
d---- 2022/12/6 下午 04:51 ESD
d---- 2023/1/6 上午 10:18 Intel
d---- 2022/5/7 下午 01:24 PerfLogs
d---- 2022/12/27 下午 04:43 platform-tools
d-r-- 2023/1/3 下午 04:49 Program Files
d-r-- 2023/1/3 下午 04:57 Program Files (x86)
d-r-- 2022/10/28 下午 05:38 Users
d---- 2022/12/27 下午 04:54 Windows
d---- 2023/1/4 下午 01:33 XboxGames
-a--- 2022/11/30 下午 06:03 12288 DumpStack.log
```
:::
### 新增物件
有點像linux的touch 可以使用這個指令創建許多不同的檔案
```ps1
New-Item
```
:::spoiler Example 1創建lnk(捷徑檔)
```ps1
PS C:\Users> New-Item -ItemType SymbolicLink -Path .\notepad.lnk -Target C:\Windows\notepad.exe
Directory: C:\Users\
Mode LastWriteTime Length Name
---- ------------- ------ ----
la--- 2023/1/6 下午 09:57 0 notepad.lnk -> C:\Windows\notepad.exe
PS C:\Users> ls
Mode LastWriteTime Length Name
---- ------------- ------ ----
la--- 2023/1/6 下午 09:57 0 notepad.lnk ->
```
:::
:::spoiler Example 2 創建一般檔案
```ps1
PS C:\Users> ls
PS C:\Users> New-Item test.txt
Directory: C:\Users
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a--- 2023/1/6 上午 10:47 0 test.txt
PS C:\Users> ls
Directory: C:\Users
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a--- 2023/1/6 上午 10:47 0 test.txt
```
:::
### 新增資料夾
在當前路徑創建一個資料夾
```ps1
mkdir
New-Item -ItemType Dircetory [dirname]
```
:::spoiler Example 1
```ps1
PS C:\Users>mkdir ccccchhhheeenng
PS C:\Users>cd ccccchhhheeenng
PS C:\Users\ccccchhhheeenng>
```
:::
:::spoiler Example 2
```ps1
PS C:\Users> ls
PS C:\Users> mkdir ccccchhhheeenng
Directory: C:\Users
Mode LastWriteTime Length Name
---- ------------- ------ ----
d---- 2023/1/6 上午 10:51 ccccchhhheeenng
PS C:\Users> cd .\ccccchhhheeenng\
PS C:\Users\ccccchhhheeenng>
```
:::
### 萬用字元
方便選種檔案 符號為"\*"
假如要選中當前路徑的所有檔案:*.*
:::spoiler Example
```
#from learn.microsoft.com
Get-ChildItem -Path C:\Temp\
Directory: C:\Temp
Mode LastWriteTime Length Name
---- ------------- ------ ----
d----- 5/15/2019 6:45 AM 1 One
d----- 5/15/2019 6:45 AM 1 Two
d----- 5/15/2019 6:45 AM 1 Three
New-Item -Path C:\Temp\* -Name temp.txt -ItemType File | Select-Object FullName
FullName
--------
C:\Temp\One\temp.txt
C:\Temp\Three\temp.txt
C:\Temp\Two\temp.txt
```
:::
### 移動檔案
將檔案或資料夾複製到指定位址
```ps1
Move-Item
mi
mv
move
```
### 複製檔案
```ps1
PS C:\Users\ccccchhhheeenng>xcopy /e /i [file] [target locate]
```
:::spoiler Example
```ps1
PS C:\Users\ccccchhhheeenng>xcopy /e /i .\test.ps1 D:
PS C:\Users\ccccchhhheeenng>D:
PS D:\>dir
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a--- 2023/1/5 下午 12:16 1033 test.ps1
```
:::
有關xcopy的其他功能:
https://learn.microsoft.com/zh-tw/windows-server/administration/windows-commands/xcopy
### 輸入
```ps1
$x=Read-Host (prompt "")[輸入提示]
```
:::spoiler Example
```ps1
PS C:\> $n=Read-Host -Prompt "Write Your Name"
Write Your Name: ccccchhhheeenng
PS C:\> Write-Output "Hello $n"
Hello ccccchhhheeenng
```
:::
### 輸出
```ps1
Write-Ouput
echo
write
```
:::spoiler Example
```ps1
PS C:\> $n=Read-Host -Prompt "Write Your Name"
Write Your Name: ccccchhhheeenng
PS C:\> Write-Output "Hello $n"
Hello ccccchhhheeenng
```
:::
## 判定式
### if else
```ps1
if(){
}else{
}
```
if()內可放where偵測物件 會自動轉成布林值
## 功能
### winget
Windows 21H2後系統預裝程式
在MSStore中名為應用程式安裝程式
可用來安裝、更新當前系統程式
```
winget
```
:::spoiler Example 1
```
PS C:\> winget install winrar
找到 WinRAR [RARLab.WinRAR] 版本 6.24.0
此應用程式已由其擁有者授權給您。
Microsoft 不負任何責任,也不會授與協力廠商封裝的任何授權。
正在下載 https://www.rarlab.com/rar/winrar-x64-624tc.exe
██████████████████████████████ 3.68 MB / 3.68 MB
已成功驗證安裝程式雜湊
正在啟動套件安裝...
已成功安裝
```
:::
:::spoiler Example 2
```ps1!
PS C:\> winget uninstall RARLab.WinRAR
找到 WinRAR [RARLab.WinRAR]
正在啟動套件解除安裝...
已成功解除安裝
```
:::
:::spoiler Example 3
```ps1
PS C:\Users>winget list
名稱 識別碼 版本 可用 來源
-----------------------------------------------------------------------------------------------------------------------
Microsoft Edge Microsoft.Edge 108.0.1462.54 108.0.1462.76 winget
```
:::
### 大於、小於、等於
| 功能|指令
| -------- | -------- |
|大於|-gt|
|小於|-lt|
|大於等於|-ge|
|小於等於|-le|
|相等|-eq|
|不等|-ne|
:::spoiler Example
```ps1
PS C:\Users\Admin> (1 -eq 1) -and (1 -eq 2)
False
PS C:\Users\Admin> (1 -eq 1) -or (1 -eq 2)
True
```
:::
## 運算
可直接使用運算符號
直接看這篇:
https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_arithmetic_operators?view=powershell-7.3
## 迴圈
基本上跟C++的迴圈一樣
:::spoiler Example
input:
```ps1=
3
```
code:
```ps1=
$a=Read-Host
for ($i = 0; $i -lt $a; $i++) {
Write-Output $i
}
Write-Output --
$i=0
while ($i -lt $a) {
Write-Output $i
$i++
}
```
output:
```
0
1
2
--
0
1
2
```
:::
## function
可以稍微簡化程式 將其中一部分有功能的程式碼先行獨立出來
等到需要時再呼叫
**仍在學習使用para、呼叫function中部分指令**
將前面學的if else加入後 寫出一個簡易的程式
:::spoiler Example 1
#### 環境:當前有一個記事本在運行
input:
```=
notepad
```
code:
```ps1
function listprocess {
$value=Get-Process|Where-Object{$_.Name -match $a}
return $value
}
function processcount {
return $output.count
}
$a=Read-Host
$output=listprocess
$processcnt=processcount
Write-Output $output
if ($processcnt -eq 1){
Write-Output "There is $processcnt process running"
}elseif ($processcnt -eq 0) {
Write-Output "process not found"
}else {
Write-Output "There are $processcnt process running"
}
```
output:
```=
NPM(K) PM(M) WS(M) CPU(s) Id SI ProcessName
------ ----- ----- ------ -- -- -----------
39 86.89 72.32 0.44 7048 1 Notepad
There is 1 process running
```
:::
:::spoiler Example 2
#### 環境:當前有三個記事本在運行
input:
```=
notepad
```
code:
```ps1
function listprocess {
$value=Get-Process|Where-Object{$_.Name -match $a}
return $value
}
function processcount {
return $output.count
}
$a=Read-Host
$output=listprocess
$processcnt=processcount
Write-Output $output
if ($processcnt -eq 1){
Write-Output "There is $processcnt process running"
}elseif ($processcnt -eq 0) {
Write-Output "process not found"
}else {
Write-Output "There are $processcnt process running"
}
```
output:
```
NPM(K) PM(M) WS(M) CPU(s) Id SI ProcessName
------ ----- ----- ------ -- -- -----------
39 87.05 72.64 0.47 7048 1 Notepad
40 87.19 72.50 0.48 11532 1 Notepad
39 86.15 73.16 0.41 21272 1 Notepad
There are 3 process running
```
:::
:::spoiler Example 3
#### 環境:當前沒有記事本在運行
input:
```=
notepad
```
code:
```ps1
function listprocess {
$value=Get-Process|Where-Object{$_.Name -match $a}
return $value
}
function processcount {
return $output.count
}
$a=Read-Host
$output=listprocess
$processcnt=processcount
Write-Output $output
if ($processcnt -eq 1){
Write-Output "There is $processcnt process running"
}elseif ($processcnt -eq 0) {
Write-Output "process not found"
}else {
Write-Output "There are $processcnt process running"
}
```
output:
```
process not found
```
:::
## 彈出提示框
可以彈出簡單的提示框
並在選擇選項後做出回應
```ps1
$prompt=New-Object -ComObject WScript.Shell
$value=prompt.popup("text",[time],"title",$a+$b)
```
其中$a $b分別為設定按鈕型式 設定圖示
if time -lt 0{提示框不自動消失}
$value中的值為使用者選擇的按鈕對應的數字
詳見:
https://learn.microsoft.com/en-us/previous-versions//x83z1d9f(v=vs.85)?redirectedfrom=MSDN
:::spoiler Example
```ps1
$prompt=New-Object -ComObject WScript.Shell
$value=$prompt.popup("Tap the button to answer",0,"Are you happy now?",4+32)
switch ($value) {
6{$msg="Good"}
7{$msg="Cheer Up"}
}
$prompt.Popup($msg)
```
:::
## 多重判斷
當一個變數可能有多種結果時
可以不用瘋狂if else
```
switch($n){
1{
??
}
2{
??
}
}
```
當$n=1時
執行後面的指令
:::spoiler Example
```ps1
$prompt=New-Object -ComObject WScript.Shell
$value=$prompt.popup("Tap the button to answer",5,"Are you happy now?",4+32)
switch ($value) {
6{$msg="Good"}
7{$msg="Cheer Up"}
-1{$msg="Anyone here?"}
}
$prompt.Popup($msg)
```
:::
## 寫出一個實用的程式
寫出一個輸入處理程序名稱就可以結束處理程序的程式
並添加一些人性化功能
:::spoiler code
```ps1=
function show-processmatch {
$q=$(Get-Process|Where-Object{$_.Name -match $a})
return $q
}
function stop-all-process {
$q=show-processmatch
Stop-Process -InputObject $q
}
function get-processmatch {
$n=(Get-Process |Where-Object{($_.Name) -match $a}).count
return $n
}
function write-killed {
Get-Process | Where-Object {$_.HasExited}
}
function promptout {
$prompt=New-Object -ComObject WScript.Shell
$rt=$prompt.popup("There are $cnt process running",0,"Are Tou Sure?",1+48)
return $rt
}
#--------------------
Out-Null
$a=Read-Host -Prompt "processname"
$q=show-processmatch
$cnt=get-processmatch
if ($cnt -ne 0) {
if($cnt -eq 1){
Stop-Process -Name $a
write-killed
Write-Output "The process has been killed"
}else{
write-output $q
Write-Output "Choose the process you want to kill,input a to kill all"
$id=Read-Host -Prompt "pid"
if ($id -eq "a"){
$tof=promptout
switch ($tof) {
1{
stop-all-process
Write-Output "All of the process has been killed"}
2{
Write-Output canceld
continue
}
}
}else{
Stop-Process -id $id
Write-Output "The process has been killed"
}
}
}else{
Write-Output "Process not found"
}
```
:::
## 最後
在powershell中安裝ps2exe模組 並將此程式轉成exe
便可使用
安裝環境
```ps1
install-module ps2exe
import-module ps2exe
```
:::spoiler 使用Terminal輸出
```ps1
PS C:\Users\ccccchhhheeenng\Documents> ps2exe .\stop-process.ps1 .\stop-process.exe
PS2EXE-GUI v0.5.0.28 by Ingo Karstein, reworked and GUI support by Markus Scholtes
PowerShell Desktop environment started...
Reading input file C:\Users\ccccchhhheeenng\Documents\stop-process.ps1
Compiling file...
Output file C:\Users\ccccchhhheeenng\Documents\stop-process.exe written
PS C:\Users\ccccchhhheeenng\Documents> ls
Directory: C:\Users\ccccchhhheeenng\Documents
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a--- 2023/1/7 上午 10:47 34304 stop-process.exe
-a--- 2023/1/7 上午 10:47 3374 stop-process.ps1
```
:::
## 運行結果
### 環境下有三個notepad在運行

輸入a後跳出提示框

選擇是 所有的notepad已被中止
並列出關閉的執行緒

運行結束
### 環境下有一個notepad在執行

直接關閉該程式
運行結束
### 環境下沒有notepad在執行

未發現程式
運行結束
https://github.com/ccccchhhheeenng/powershell/tree/main/%E6%88%90%E6%9E%9C