ページ概要
本ページでは、Microsoft Intuneを利用してWindowsデバイスに対してJOSYSブラウザ拡張機能をサイレントインストール/アクティベーションする際に必要となるスクリプトのサンプルを掲示しております。
Intuneを使ってWindowsデバイスに拡張機能をサイレントインストール・アクティベーションする方法(2/2)にて、ケースC(各ユーザーがデバイスの管理者権限を持っておらずUPNがジョーシス上のメールアドレスと同じ)だった方向けです。
想定読者
JOSYSブラウザ拡張機能の一括展開を計画・実施されるご担当者様。
ブラウザ拡張機能について
ブラウザ拡張機能に関する情報は、下記のページをお先にご覧ください。
1.ブラウザ拡張機能について
2.ブラウザ拡張機能のご利用方法
注意点
⚠️<ケースCをご利用のお客様>
ケースCはスクリプトが二つあります。
1つ目のスクリプトを実行していただき、Intune上で成功していることと
対象のユーザーの環境に反映されていることを確認してから、2つ目のスクリプトを実行してください。
対象のユーザーの環境に反映されているか確認する方法は、下記の通りです。
1.対象のユーザーのPowerShellを起動
2.echo $env:MY_UPN と入力
3.Enterを押し、ジョーシスのメンバー台帳に登録されているメールアドレスが表示されることを確認する
ケースCはスクリプトが二つあります。
1つ目のスクリプトを実行していただき、Intune上で成功していることと
対象のユーザーの環境に反映されていることを確認してから、2つ目のスクリプトを実行してください。
対象のユーザーの環境に反映されているか確認する方法は、下記の通りです。
1.対象のユーザーのPowerShellを起動
2.echo $env:MY_UPN と入力
3.Enterを押し、ジョーシスのメンバー台帳に登録されているメールアドレスが表示されることを確認する
1つ目のスクリプト
スクリプトは全部で2つあります。
まずは下記のスクリプトをユーザーコンテキストで実施するため、保存してください。
- 下記のスクリプトをコピーし、メモ帳などに貼り付けてください。
- ファイル名を「set_josys_user_upn.ps1」として保存してください。
- ファイルの種類が「Windows PowerShellスクリプト」となっていることを確認してください。
# スクリプト: SetUserUpnToEnvironmentVariable.ps1
# 環境変数名を指定します (例: MY_UPN)
$environmentVariableName = "MY_UPN"
try {
# whoami /upn を実行して出力を取得
Write-Host "Executing 'whoami /upn' to retrieve UPN..."
$upnOutput = whoami /upn 2>&1 # 標準エラーもキャプチャ
# whoami コマンドが成功したか確認 (終了コードが0か)
if ($LASTEXITCODE -ne 0) {
Write-Warning "Failed to execute 'whoami /upn'. Output: $upnOutput"
# UPNが取得できなかった場合、エラーメッセージを表示して終了することも検討
# exit 1 # 必要に応じて
} else {
# 出力からUPNを抽出 (通常は1行で表示されるはず)
$upn = $upnOutput.Trim()
if ([string]::IsNullOrWhiteSpace($upn)) {
Write-Warning "UPN could not be determined or is empty."
# UPNが空の場合の処理
} else {
Write-Host "UPN retrieved: $upn"
# ユーザー環境変数を設定 (永続的)
# [System.Environment]::SetEnvironmentVariable(環境変数名, 値, スコープ)
# スコープ: "User", "Machine", "Process"
Write-Host "Setting user environment variable '$environmentVariableName' to '$upn'..."
[System.Environment]::SetEnvironmentVariable($environmentVariableName, $upn, [System.EnvironmentVariableTarget]::User)
if ($?) { # 直前の操作が成功したか確認
Write-Host "User environment variable '$environmentVariableName' has been set successfully."
Write-Host "Please note: You may need to open a new command prompt or PowerShell session, or restart applications for the change to take effect."
} else {
Write-Warning "Failed to set user environment variable '$environmentVariableName'."
}
}
}
} catch {
Write-Error "An unexpected error occurred: $($_.Exception.Message)"
}
# スクリプト終了
2つ目のスクリプト
- 下記のスクリプトをコピーし、メモ帳などに貼り付けてください。
- 3行目の YOUR_ORGANIZATION_KEY をジョーシス上で確認した自社の組織IDに変更してください。
- ファイル名を「josys-extension-config.ps1」として保存してください。
- ファイルの種類が「Windows PowerShellスクリプト」となっていることを確認してください。
- Intuneを使ってWindowsデバイスに拡張機能をサイレントインストール・アクティベーションする方法(2/2) - 2.スクリプトを対象デバイスに適用するに戻って作業を進めてください。
# --- Configuration Settings ---
# Set the OrganizationKey value here (Mandatory)
$organizationKey = "YOUR_ORGANIZATION_KEY" # Replace with your actual key
# Relative registry key paths under HKCU for the specific extensions
$chromeRelativePath = "Software\Policies\Google\Chrome\3rdparty\extensions\moaklgcgokbgplldonjkoochhlefkbjf\policy"
$edgeRelativePath = "SOFTWARE\Policies\Microsoft\Edge\3rdparty\extensions\hjifncajikcdkhlofdjjlhcjoennmdfc\policy"
# --- End of Configuration Settings ---
# --- Script Body ---
Write-Host "Script started for Chrome and Edge extension policies. OrganizationKey: '${organizationKey}'"
Write-Host "This script will attempt to read the UPN from the user's 'MY_UPN' environment variable."
# Basic check if OrganizationKey is set
if ([string]::IsNullOrWhiteSpace($organizationKey) -or $organizationKey -eq "YOUR_ORGANIZATION_KEY_HERE") {
Write-Error "Please set a valid value for the `${organizationKey}` variable at the top of the script."
exit 1
}
# Function to get the active user session username (to find the user's SID)
function Get-ActiveUserSessionInfo {
try {
$queryOutput = query user
$activeSessionLine = $queryOutput | Select-String -Pattern '^\s*>' | Select-Object -First 1
if ($activeSessionLine) {
$sessionInfo = $activeSessionLine.Line -split '\s+' | Where-Object {$_}
if ($sessionInfo.Count -ge 2) {
$userName = $sessionInfo[1]
Write-Host "Detected active user for SID targeting: '${userName}' using query user."
return $userName
} else {
Write-Warning "Unexpected output format from query user for SID targeting. Line: $($activeSessionLine.Line)"
}
} else {
Write-Warning "Could not find an active session using query user for SID targeting."
}
} catch {
Write-Warning "Failed to execute query user command for SID targeting: $($_.Exception.Message)"
}
try {
Write-Host "Fallback for SID targeting: Attempting to get username from Win32_ComputerSystem..."
$computerSystem = Get-CimInstance -ClassName Win32_ComputerSystem
if ($computerSystem.UserName) {
Write-Host "Retrieved username for SID targeting: '$($computerSystem.UserName)' from Win32_ComputerSystem."
if ($computerSystem.UserName -like "*\*" -or $computerSystem.UserName -like "*@*") {
return $computerSystem.UserName
} else {
Write-Warning "Username from Win32_ComputerSystem for SID targeting ('$($computerSystem.UserName)') is not in the expected format."
}
} else {
Write-Warning "Could not retrieve username from Win32_ComputerSystem for SID targeting."
}
} catch {
Write-Error "Error retrieving username for SID targeting from Win32_ComputerSystem: $($_.Exception.Message)"
}
Write-Error "Could not determine the active user for SID targeting."
return $null
}
# Get the active username to determine the target user's SID
$activeUserNameForSid = Get-ActiveUserSessionInfo
if (-not $activeUserNameForSid) {
Write-Error "No target user found for SID resolution. Exiting script."
exit 1
}
# Get User's SID
$userSid = $null
try {
$ntAccount = New-Object System.Security.Principal.NTAccount($activeUserNameForSid)
$userSid = $ntAccount.Translate([System.Security.Principal.SecurityIdentifier]).Value
Write-Host "Retrieved SID for user '${activeUserNameForSid}': ${userSid}"
} catch {
Write-Error "Failed to retrieve SID for user '${activeUserNameForSid}': $($_.Exception.Message)"
exit 1
}
# Get the value for 'UserEmail' from the user's 'MY_UPN' environment variable (via registry)
$userEmailValueFromEnv = $null
if ($userSid) {
try {
$envRegPath = "Registry::HKEY_USERS\${userSid}\Environment"
Write-Host "Attempting to read 'MY_UPN' environment variable from user registry path: ${envRegPath}"
# Check if the registry path itself exists
if (Test-Path $envRegPath) {
$myUpnProperty = Get-ItemProperty -Path $envRegPath -Name "MY_UPN" -ErrorAction SilentlyContinue
if ($myUpnProperty -and $myUpnProperty.PSObject.Properties["MY_UPN"]) { # More robust check for property existence
$userEmailValueFromEnv = $myUpnProperty.MY_UPN.Trim()
if ([string]::IsNullOrWhiteSpace($userEmailValueFromEnv)) {
Write-Warning "User environment variable 'MY_UPN' was found for SID ${userSid} but is empty or whitespace."
$userEmailValueFromEnv = $null # Ensure it's null if empty
} else {
Write-Host "Successfully retrieved 'MY_UPN' for SID ${userSid}: '${userEmailValueFromEnv}'"
}
} else {
Write-Warning "User environment variable 'MY_UPN' not found for SID ${userSid} at ${envRegPath}."
}
} else {
Write-Warning "User environment registry path not found for SID ${userSid}: ${envRegPath}"
}
} catch {
Write-Error "An exception occurred while trying to read 'MY_UPN' from user registry for SID ${userSid}: $($_.Exception.Message)"
}
} else {
Write-Error "User SID was not resolved, cannot read user-specific environment variable."
}
# If MY_UPN is required and not found/empty, exit.
if (-not $userEmailValueFromEnv) {
Write-Error "Failed to obtain a valid value from user environment variable 'MY_UPN'. This value is required for 'UserEmail'. Exiting script."
exit 1
}
# Proceed with registry operations only if SID and userEmailValueFromEnv were obtained
if ($userSid -and $userEmailValueFromEnv) {
# --- Process Chrome Path ---
$chromeUserRegistryPath = "Registry::HKEY_USERS\${userSid}\${chromeRelativePath}"
Write-Host "--- Processing Chrome Path: ${chromeUserRegistryPath} ---"
try {
if (-not (Test-Path -Path $chromeUserRegistryPath)) {
Write-Host "Chrome registry key does not exist. Creating..."
New-Item -Path $chromeUserRegistryPath -Force -ErrorAction Stop | Out-Null
Write-Host "Successfully created Chrome registry key '${chromeUserRegistryPath}'."
} else {
Write-Host "Chrome registry key already exists."
}
$CurrentErrorActionPreference = $ErrorActionPreference
$ErrorActionPreference = "SilentlyContinue"
New-ItemProperty -Path $chromeUserRegistryPath -Name "UserEmail" -Value $userEmailValueFromEnv -PropertyType String -Force
if ($?) { Write-Host "Successfully set Chrome 'UserEmail' to '${userEmailValueFromEnv}'." }
else { Write-Error "Failed to set Chrome 'UserEmail'. Last Error: $($error[0].Exception.Message)" }
New-ItemProperty -Path $chromeUserRegistryPath -Name "OrganizationKey" -Value $organizationKey -PropertyType String -Force
if ($?) { Write-Host "Successfully set Chrome 'OrganizationKey' to '${organizationKey}'." }
else { Write-Error "Failed to set Chrome 'OrganizationKey'. Last Error: $($error[0].Exception.Message)" }
$ErrorActionPreference = $CurrentErrorActionPreference
} catch {
Write-Error "Failed processing Chrome registry path '${chromeUserRegistryPath}': $($_.Exception.Message)"
}
Write-Host "--- Finished Processing Chrome Path ---"
# --- Process Edge Path ---
$edgeUserRegistryPath = "Registry::HKEY_USERS\${userSid}\${edgeRelativePath}"
Write-Host "--- Processing Edge Path: ${edgeUserRegistryPath} ---"
try {
if (-not (Test-Path -Path $edgeUserRegistryPath)) {
Write-Host "Edge registry key does not exist. Creating..."
New-Item -Path $edgeUserRegistryPath -Force -ErrorAction Stop | Out-Null
Write-Host "Successfully created Edge registry key '${edgeUserRegistryPath}'."
} else {
Write-Host "Edge registry key already exists."
}
$CurrentErrorActionPreference = $ErrorActionPreference
$ErrorActionPreference = "SilentlyContinue"
New-ItemProperty -Path $edgeUserRegistryPath -Name "UserEmail" -Value $userEmailValueFromEnv -PropertyType String -Force
if ($?) { Write-Host "Successfully set Edge 'UserEmail' to '${userEmailValueFromEnv}'." }
else { Write-Error "Failed to set Edge 'UserEmail'. Last Error: $($error[0].Exception.Message)" }
New-ItemProperty -Path $edgeUserRegistryPath -Name "OrganizationKey" -Value $organizationKey -PropertyType String -Force
if ($?) { Write-Host "Successfully set Edge 'OrganizationKey' to '${organizationKey}'." }
else { Write-Error "Failed to set Edge 'OrganizationKey'. Last Error: $($error[0].Exception.Message)" }
$ErrorActionPreference = $CurrentErrorActionPreference
} catch {
Write-Error "Failed processing Edge registry path '${edgeUserRegistryPath}': $($_.Exception.Message)"
}
Write-Host "--- Finished Processing Edge Path ---"
} else {
# This case should generally be covered by earlier exits if $userSid or $userEmailValueFromEnv are not obtained.
Write-Error "Cannot perform registry operations because SID or UserEmail value (from MY_UPN env var) could not be obtained."
exit 1
}
Write-Host "Script execution finished."