2024年4月19日 星期五

pnp.powershell 基本用法

pnp.powershell 基本用法

經常要測試,每次都從頭來有點煩了把常見的語法整合起來



安裝

安裝有分好幾個版本,比較要注意的是從2版開始必須要 pwsh7 才能動,環境不允許的話只能裝舊版的。

各版本可以從這裡點出來
powershell/README.md at dev · pnp/powershell (github.com)


夜間最新版

Install-Module -Name PnP.PowerShell -AllowPrerelease

最新穩定版 (PowerShell Gallery | PnP.PowerShell 2.4.0)

Install-Module -Name PnP.PowerShell -RequiredVersion 2.4.0

舊版

Install-Module PnP.PowerShell -RequiredVersion 1.12.0 -Force


基於版本問題,建議在代碼中把這段放進去開頭,可以少走不少彎路

function GetDateString { $((Get-Date).Tostring("yyyy/MM/dd HH:mm:ss.fff")) }
$Module = (Get-Module -ListAvailable PnP.PowerShell)[0]
if (!$Module) { Write-Error "The module 'PnP.PowerShell' is not installed." -EA 1 }
Write-Host "[$(GetDateString)] " -ForegroundColor DarkGray -NoNewline
Write-Host "PowerShellVersion $($PSVersionTable.PSVersion), PnP.PowerShellVersion $($Module.Version)" -ForegroundColor DarkGray

注意看 Get-Module 有用 [0] 取第一個,如果同時存在多個版本的話



登入

登入有好幾種方法,先介紹文字介面的

$SiteUrl = "https://chg.sharepoint.com/sites/Maple"
$User    = "UserName@chg.onmicrosoft.com"
$PWord   = "PassWord"
$PWord = $PWord | ConvertTo-SecureString -AsPlainText -Force
$Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, $PWord
Connect-PnPOnline -Url $SiteUrl -Credentials $Credential


這樣就登入了,再來可以用這個測試現在登入哪個網站

# 目前登入的用戶
(Get-PnPConnection).PSCredential

# 目前登入的網站
Get-PnPWeb


對於如何合理的儲存資料,可以參考這個專案https://github.com/hunandy14/ConvertFrom-Env 



上傳檔案

這邊要注意一點是斜線的方向,一開始不知道弄了好一會兒。


先用預設的資料夾測試,這個是創建SharePoint時預設會建立的文件庫。

# 獲取預設資料夾
Get-PnPFolder -Url "/Shared Documents"

# 獲取預設資料夾中的子資料夾
Get-PnPFolder -Url "/Shared Documents/File"


創建資料夾

try { # 檢查資料夾是否存在
    Get-PnPFolder -Url "/Shared Documents/File" -ErrorAction Stop
} catch { # 如果資料夾不存在,則建立它
    Add-PnPFolder -Name "File" -Folder "Shared Documents"
}


上傳文件

Add-PnPFile -Path ".\README.md" -Folder "Shared Documents/File"


查看文件

Get-PnPFile -Url "Shared Documents/File/README.md"






沒有留言:

張貼留言