bat 與 PowerShell 的結(jié)合使用
前言
背景: 前前段時(shí)間,做文件操作處理時(shí),有這么一個(gè)場(chǎng)景: window 下需要對(duì)某固定目錄下的文件及其他文件進(jìn)行拷貝操作, 至目標(biāo)對(duì)象---> 外置存儲(chǔ)設(shè)備(U盤(pán)或移動(dòng)硬盤(pán)),且需要一定大小的存儲(chǔ)量并做判斷提示。
問(wèn)題: 其主要問(wèn)題不在文件拷貝操作,而是對(duì)外置存儲(chǔ)設(shè)備的處理(主要是對(duì)磁盤(pán)大小的判斷,也就是數(shù)字的比較及計(jì)算)。首先批處理的數(shù)字處理有一定范圍(正負(fù) 2^31-1),其次超出范圍的比較情況還有不同。
解決: 其一則是正面剛(截取操作再比較),其二則是繞過(guò)換其他方法(調(diào) PowerShell 處理)
一、使用 bat 做數(shù)字比較
1.下圖為批處理數(shù)字比較的情況:兩個(gè)值都超出范圍的比較,結(jié)果相反

2.以下為當(dāng)時(shí)的腳本(后面磁盤(pán)大小的計(jì)算實(shí)在不知道咋怎,用了 PowerShell ):
@echo off & setlocal enabledelayedexpansion
rem =========================================================
rem == The tools develop for copy files to external disk ==
rem == author: by zzw ==
rem == datetime: 2019.07.1 ==
rem =========================================================
@rem chcp 936 ::更換默認(rèn)編碼
@rem 源路徑
set srcPath=F:\zzwTest
@rem 本地磁盤(pán)驅(qū)動(dòng)器: C:\ D:\ E:\
:HasDrive
for /f "tokens=1,* delims= " %%i in ('fsutil fsinfo drives') do (
set d=%%j
set d=!d:\=!
@rem echo !d!. 遍歷磁盤(pán)信息是否包含 移動(dòng) 字符
for %%a in (!d!) do (
fsutil fsinfo driveType %%a | findstr "移動(dòng)" >nul && set driver=%%a
)
@rem 移動(dòng)硬盤(pán)會(huì)被指定為固定驅(qū)動(dòng)器.需要去除本地磁盤(pán)
if not defined driver (
set d=!d:C:=!
set d=!d:D:=!
set d=!d:E:=!
set d=!d: =!
set driver=!d!
if "!d!"=="" ( call :Tip1 ) else ( call :Tip1 ZZW )
)
goto DriverSpace
)
:DriverSpace
if defined driver (
@rem 包含 可用字節(jié)總數(shù) 的行,取第一行
for /f "tokens=1,2 delims=:" %%i in ('fsutil volume diskFree %driver% ^|findstr "可用字節(jié)總數(shù)"') do (
set free=%%j
@rem echo !free! | findstr "(" && set free=!free:*(=! & set free=!free:^)=! || set free=!free: =!
for /f "tokens=1 delims= " %%x in ("!free!") do (
set free=%%x
)
@rem calculate disk size. multiplier of 1.1
@rem debug: set free=1048576000
if !free! LSS 1126 ( call :Tip3 1 B )
if !free! LSS 1153433 ( call :Tip3 1024 KB )
if !free! LSS 1181116006 ( call :Tip3 1024*1024 MB )
call :Tip3 1024*1024*1024 GB
:Below
@rem 批處理數(shù)值范圍在正負(fù) 2^31-1 = 2147483647
set total=!free!t
if "!total:~10!"=="" (
@rem echo 小于 10 位數(shù) 0.93GB=999999999B 0.5GB=536870912B
if "!total:~8!"=="" ( call :Tip2 [10MB] ★★★警告★★★)
if "!total:~9!"=="" ( call :Tip2 [100MB] ★★★警告★★★)
set totalN=!total:~0,9!
if !totalN! LSS 104857600 ( call :Tip2 [100MB] ★★★警告★★★)
if !totalN! LSS 262144000 ( call :Tip2 [250MB] ★★★警告★★★)
if !totalN! LSS 536870910 ( call :Tip2 [500MB] ★★★警告★★★)
call :Tip2 [1GB]
)
if "!total:~10!"=="t" (
@rem echo 等于 10 位數(shù) 6GB=6442450944B
set totalA=!total:~0,10!
if !totalA! LSS 1048576000 ( call :Tip2 [1GB] )
if !totalA! LSS 1610612735 ( call :Tip2 [1.5GB] )
if !totalA! LSS 2147483646 ( call :Tip2 [2GB] )
set totalB=!total:~0,9!
if !totalB! LSS 268435456 ( call :Tip2 [2.5GB] )
if !totalB! LSS 322122547 ( call :Tip2 [3GB] )
if !totalB! LSS 429496729 ( call :Tip2 [4GB] )
if !totalB! LSS 536870912 ( call :Tip2 [5GB] )
if !totalB! LSS 644245094 ( call :Tip2 [6GB] )
)
goto ReSelect
)
)
:Tip1
color 0b & echo,
echo 請(qǐng)確保外置 [U盤(pán)] 或 [移動(dòng)硬盤(pán)] 插入成功!!!& echo,
if not "%1"=="" ( echo 磁盤(pán)識(shí)別錯(cuò)誤,請(qǐng)聯(lián)系開(kāi)發(fā)者 ----^> %1& echo, )
goto End
:Tip2
color 0b & echo,
echo 請(qǐng)確保 %driver% 盤(pán)空間至少 6GB 可用 & echo,
if not "%2"=="" echo %2
echo 注意 %driver% 盤(pán)空間小于 %1 ,不建議繼續(xù)操作,默認(rèn) N
echo 若繼續(xù)將可能導(dǎo)致部分文件復(fù)制失敗!!!
echo,
set /p confirm=請(qǐng)確認(rèn)是否要繼續(xù)(N/Y)_^>^>
if /i %confirm%==y goto ReSelect
goto End
:Tip3
set /p =◆ %driver% 磁盤(pán)可用空間(約)為: <nul
@rem powershell -c "[String]$i=!free!/(%1);if($i.contains('.')) {$s=$i.split('.'); $s[0],$s[1].substring(0,3)+'%2' -join('.')} else {$i+'%2'}"
powershell -c "[String]$i=!free!/(%1);if($i.contains('.')) {$s=$i.split('.'); $s[0]+'.'+$s[1].substring(0,3)+' %2'} else {$i+'%2'}"
goto Below
:ReSelect
color 0a
echo,
echo *********該工具將拷貝所選目錄文件至 %driver% 盤(pán)設(shè)備********
echo,
echo 請(qǐng)?jiān)谙铝羞x項(xiàng)中選擇需要操作的路徑(如: 1 、2 、3 )
echo,
echo ==========================================================
set a=0
for /f %%i in ('dir /b /ad "%srcPath%"') do (
set /a a+=1
echo [!a!] %%i
)
echo,
echo ==========================================================
set a=0
set /p number=請(qǐng)輸入:
for /f %%i in ('dir /b /ad "%srcPath%"') do (
set /a a+=1
if !a!==%number% set testResult=%%i & echo, & echo 你的選擇是 %%i
)
if not defined testResult (
color 04
echo,
echo 請(qǐng)選擇正確的選項(xiàng)!
echo 請(qǐng)按任意鍵重新選擇!
pause >nul & cls & goto ReSelect
)
echo,
echo "=====可以開(kāi)始操作了======"
:End
pause
從以上腳本看來(lái),在 cmd 中使用大的數(shù)據(jù)比較時(shí)非常吃力,腳本還一坨一坨的。而 PowerShell 則簡(jiǎn)單了,請(qǐng)看下列分析及操作操作。
二、CMD 命令行 PowerShell 的使用
在使用前首先來(lái)介紹下:
Windows PowerShell 是一種命令行外殼程序和腳本環(huán)境,使命令行用戶(hù)和腳本編寫(xiě)者可以利用 .NET Framework的強(qiáng)大功能 ----->百度百科
1.在cmd 命令行中 powershell /? 先查看簡(jiǎn)要幫助文檔(以下為比較關(guān)注信息),這里順便貼上官方路徑

2.若要運(yùn)行PowerShell 腳本或者命令,可能需要使用 PowerShell 需要開(kāi)啟相關(guān)權(quán)限,如下操作即可:
@echo off
@rem set the execution mode of the PowerShell
set flag=1
@rem -c 等同 -Command
powershell -c "Get-ExecutionPolicy" |findstr "Restricted" >nul && set flag=0
if %flag% == 0 (
:: powershell -ExecutionPolicy RemoteSigned 與下句等同
powershell -c "Set-ExecutionPolicy RemoteSigned"
echo Allowed to use powershell
)
3.著重實(shí)踐下重點(diǎn)關(guān)注的地方
PowerShell[.exe] [-PSConsoleFile <file> | -Version <version>]
[-NoLogo] [-NoExit] [-Sta] [-NoProfile] [-NonInteractive]
[-InputFormat {Text | XML}] [-OutputFormat {Text | XML}]
[-WindowStyle <style>] [-EncodedCommand <Base64EncodedCommand>]
[-File <filePath> <args>] [-ExecutionPolicy <ExecutionPolicy>]
[-Command { - | <script-block> [-args <arg-array>]
| <string> [<CommandParameters>] } ]
# Command 的值為"-", 將會(huì)打印幫助文檔 同 powershell -c
powershell -c -
# Command 的值為腳本塊,只在 powershell 環(huán)境下才有效。
# 而 cmd 下會(huì)原樣輸出,且數(shù)據(jù)必須在括號(hào)中,否則報(bào)錯(cuò)
powershell -c {Test $HOME}
# Command 的值為字符串,則該字符串必須是最后一個(gè)參數(shù)
# 執(zhí)行字符串中的命令返回結(jié)果且輸出 test
powershell -c "echo $HOME" test
# 運(yùn)行 Windows PowerShell 命令的字符串, 不會(huì)輸出 test
powershell -c "& {$HOME}" test
# 實(shí)際發(fā)現(xiàn)省略 -c 命令也可以實(shí)現(xiàn)(暫未深入研究其原因)
powershell $HOME
結(jié)果如圖:

三、使用 PowerShell 做數(shù)字比較
1.通過(guò)上述的幫助文檔,就可以愉快的做數(shù)字比較和計(jì)算了。不過(guò)這里還是列一下 PowerShell 的比較運(yùn)算符,其他還是移步官方文檔或文末鏈接地址查閱。
-eq:等于 -ne:不等于
-gt:大于 -ge:大于等于
-lt:小于 -le:小于等于
-contains:包含 -notcontains:不包含
2.再來(lái)看看數(shù)字比較和計(jì)算,可以發(fā)現(xiàn)很方便,既能通過(guò)判斷自定義顯示結(jié)果,也能直接顯示比較結(jié)果。

3.對(duì)于最開(kāi)始的磁盤(pán)空間比較計(jì)算的問(wèn)題已經(jīng)可解決了,但大串的數(shù)字寫(xiě)起來(lái)還是挺麻煩的,不過(guò) PowerShell 可以識(shí)別計(jì)算機(jī)容量單位, 包括 KB,MB,GB,TB,PB。那么我們就能更加愉快的玩耍了

@echo off
for /f "tokens=1,2 delims=:" %%i in ('fsutil volume diskFree D:\ ^|findstr "可用字節(jié)總數(shù)"') do (
@rem 計(jì)算時(shí)會(huì)進(jìn)行四舍五入
@rem 等同 powershell "'{0:N2}' -f (%%j/1GB)"
powershell "$s='{0:0.00}' -f (%%j/1GB);$s+' GB'"
)
pause
四、調(diào)用 PowerShell 的細(xì)節(jié)及場(chǎng)景
1.調(diào)用本質(zhì)
整體來(lái)說(shuō)在使用批處理時(shí)可以通過(guò) PowerShell 來(lái)彌補(bǔ)不足。究其調(diào)用本質(zhì)----> 開(kāi)啟一個(gè) PowerShell 進(jìn)程實(shí)現(xiàn)操作結(jié)束后退出。如圖所示

2.調(diào)用細(xì)節(jié)
本文中的腳本只對(duì)調(diào)用 PowerShell 的結(jié)果進(jìn)行展示,那如何賦值給變量或管道輸出呢?
# 不換行結(jié)果顯示
set /p =HomePath: <nul
powershell "$HOME"
# 輸出值賦給批處理腳本變量
for /f %%i in ('powershell "1+2"') do (
set sum=%%i
)
echo 賦值結(jié)果:%sum%
# 管道輸出給批處理的其他命令
powershell $HOST | findstr /i name
# 批處理參數(shù)傳給 PowerShell 使用
set total=100
powershell "'平均值為: '+ %total%/10"
3.其他場(chǎng)景
批處理運(yùn)行時(shí)彈框選項(xiàng)【powershell 彈框】
@echo off
echo After 3 seconds, the prompt box will appear...
timeout /t 3 >nul
set pscommand='powershell "$IP=ForEach($ip in (ipconfig) -like '*IPv4*'){'IP Address:'+($ip -split ' : ')[-1]};$showIp=New-Object -ComObject WScript.Shell;$showIp.popup(\"$IP\",0,'ShowIP',1+64)"'
for /f %%i in (%pscommand%) do (
if %%i==1 ( echo You selected the OK button )
if %%i==2 ( echo You selected the CANCEL button )
)
pause
批處理調(diào)用執(zhí)行 PowerShell 腳本文件
powershell -File .\run.ps1
未完,待續(xù)...

浙公網(wǎng)安備 33010602011771號(hào)