ページ概要
本ページでは、Microsoft Intuneを利用してWindowsデバイスに対してJosysブラウザ拡張機能をサイレントインストール/アクティベーションする際に必要となるスクリプトのサンプルを掲示しております。
Intuneを使ってWindowsデバイスに拡張機能をサイレントインストール・アクティベーションする方法(2/2)にて、ケースC(各ユーザーがデバイスの管理者権限を持っておらずUPNがJosys上のメールアドレスと同じ)だった方向けです。
想定読者
Josysブラウザ拡張機能の一括展開を計画・実施されるご担当者様。
ブラウザ拡張機能について
ブラウザ拡張機能に関する情報は、下記のページをお先にご覧ください。
1.ブラウザ拡張機能について
2.ブラウザ拡張機能のご利用方法
注意点
⚠️<ケースCをご利用のお客様>
ケースCはスクリプトが二つあります。
1つ目のスクリプトを実行していただき、Intune上で成功していることと
対象のユーザーの環境に反映されていることを確認してから、2つ目のスクリプトを実行してください。
対象のユーザーの環境に反映されているか確認する方法は、下記の通りです。
1.対象のユーザーのPowerShellを起動
2.echo $env:MY_UPN と入力
3.Enterを押し、Josysのメンバー台帳に登録されているメールアドレスが表示されることを確認する
ケースCはスクリプトが二つあります。
1つ目のスクリプトを実行していただき、Intune上で成功していることと
対象のユーザーの環境に反映されていることを確認してから、2つ目のスクリプトを実行してください。
対象のユーザーの環境に反映されているか確認する方法は、下記の通りです。
1.対象のユーザーのPowerShellを起動
2.echo $env:MY_UPN と入力
3.Enterを押し、Josysのメンバー台帳に登録されているメールアドレスが表示されることを確認する
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つ目のスクリプト
- 下記のスクリプトをコピーし、メモ帳などに貼り付けてください。
-
$organizationKeyの YOUR_ORGANIZATION_KEY をJosys上で確認した自社の組織IDに変更してください。 - ファイル名を「josys-extension-config.ps1」として保存してください。
- ファイルの種類が「Windows PowerShellスクリプト」となっていることを確認してください。
- Intuneを使ってWindowsデバイスに拡張機能をサイレントインストール・アクティベーションする方法(2/2) - 2.スクリプトを対象デバイスに適用するに戻って作業を進めてください。
<#
.SYNOPSIS
Sets the UserEmail (UPN) and OrganizationKey for Chrome and Edge extensions in the user's registry.
This script is designed to run in the SYSTEM context via Microsoft Intune.
.DESCRIPTION
1. Identifies the currently logged-in user by checking the owner of the 'explorer.exe' process.
2. Retrieves the User Principal Name (UPN) using 'dsregcmd /status' (Plan A).
If that fails, it falls back to the 'MY_UPN' environment variable in the user's registry (Plan B).
3. Writes the 'UserEmail' and 'OrganizationKey' to the HKEY_USERS hive for the active user.
4. If no active user session is found, it exits with an error code (1) to trigger an Intune retry.
.NOTES
- Run Context: System
- Log Path: %TEMP%\SetExtensionPolicy.log
#>
# ==========================================
# Configuration Settings
# ==========================================
# [MANDATORY] Set the OrganizationKey value here
$organizationKey = "YOUR_ORGANIZATION_KEY"
# Relative registry key paths for the specific extensions
$chromeRelativePath = "Software\Policies\Google\Chrome\3rdparty\extensions\moaklgcgokbgplldonjkoochhlefkbjf\policy"
$edgeRelativePath = "SOFTWARE\Policies\Microsoft\Edge\3rdparty\extensions\hjifncajikcdkhlofdjjlhcjoennmdfc\policy"
# ==========================================
# Helper Functions
# ==========================================
# Function to get the active user session (SID and Username) from the explorer.exe process
function Get-ActiveUserSession {
try {
$explorerProc = Get-CimInstance Win32_Process -Filter "Name = 'explorer.exe'" | Select-Object -First 1
# If explorer.exe is not running, the user is not fully logged in or desktop is not ready
if (-not $explorerProc) { return $null }
$owner = $explorerProc.InvokeMethod("GetOwner", $null)
if ($owner.ReturnValue -ne 0) { return $null }
$domain = $owner.Domain
$user = $owner.User
# Convert User/Domain to SID
$ntAccount = New-Object System.Security.Principal.NTAccount($domain, $user)
$sid = $ntAccount.Translate([System.Security.Principal.SecurityIdentifier]).Value
return @{
UserName = "$domain\$user"
SID = $sid
UserOnly = $user
}
} catch {
Write-Error "Error in Get-ActiveUserSession: $($_.Exception.Message)"
return $null
}
}
# Function to retrieve the UPN (UserEmail)
function Get-UserUPN {
param (
[string]$TargetSid,
[string]$TargetUserName
)
# [Plan A] Retrieve from System Registration (dsregcmd) - Recommended for Intune/Entra ID devices
try {
Write-Host "Attempting Plan A: Retrieve UPN from system registration (dsregcmd)..."
$dsreg = dsregcmd /status
$emailLine = $dsreg | Select-String "UserEmail" -Context 0,1
if ($emailLine) {
# Extract email from "UserEmail : user@example.com"
$parts = $emailLine.ToString().Split(":")
if ($parts.Count -gt 1) {
$upn = $parts[1].Trim()
if (-not [string]::IsNullOrWhiteSpace($upn)) {
Write-Host "Plan A Success: Found UPN '$upn' from system."
return $upn
}
}
}
} catch {
Write-Warning "Plan A failed or returned invalid data."
}
# [Plan B] Retrieve from User Environment Variable 'MY_UPN' via Registry
try {
Write-Host "Attempting Plan B: Retrieve UPN from User Environment Registry (MY_UPN)..."
$envPath = "Registry::HKEY_USERS\$TargetSid\Environment"
$property = Get-ItemProperty -Path $envPath -Name "MY_UPN" -ErrorAction SilentlyContinue
if ($property -and $property.MY_UPN) {
$upn = $property.MY_UPN
if (-not [string]::IsNullOrWhiteSpace($upn)) {
Write-Host "Plan B Success: Found UPN '$upn' from MY_UPN registry."
return $upn
}
}
} catch {
Write-Warning "Plan B failed."
}
# [Plan C] Fallback to username
Write-Host "Plan C: Fallback to username '$TargetUserName'."
return $TargetUserName
}
# ==========================================
# Main Execution Logic
# ==========================================
Start-Transcript -Path "$env:TEMP\SetExtensionPolicy.log" -Force
Write-Host "Script started."
# Validate Organization Key
if ([string]::IsNullOrWhiteSpace($organizationKey) -or $organizationKey -eq "YOUR_ORGANIZATION_KEY") {
Write-Error "CRITICAL ERROR: Please set a valid value for `$organizationKey in the script configuration."
Stop-Transcript
exit 1
}
# 1. Identify Target User
$activeUser = Get-ActiveUserSession
if (-not $activeUser) {
# If no active user is found (explorer.exe not running), exit with error code 1.
# This ensures Intune reports a failure and retries the script later.
Write-Error "No active user session found (explorer.exe not running yet). Returning error to trigger retry."
Stop-Transcript
exit 1
}
Write-Host "Target User: $($activeUser.UserName)"
Write-Host "Target SID: $($activeUser.SID)"
# 2. Retrieve UPN
$targetUPN = Get-UserUPN -TargetSid $activeUser.SID -TargetUserName $activeUser.UserOnly
if (-not $targetUPN) {
Write-Error "Failed to determine UPN. Exiting."
Stop-Transcript
exit 1
}
Write-Host "Final UPN to write: $targetUPN"
# 3. Write to Registry
$policies = @(
@{ Name = "Chrome"; Path = $chromeRelativePath },
@{ Name = "Edge"; Path = $edgeRelativePath }
)
foreach ($app in $policies) {
# Construct the full path to HKEY_USERS\<SID>\...
$fullPath = "Registry::HKEY_USERS\$($activeUser.SID)\$($app.Path)"
Write-Host "--- Processing $($app.Name) ---"
Write-Host "Target Registry Path: $fullPath"
try {
# Create key if it doesn't exist
if (-not (Test-Path $fullPath)) {
New-Item -Path $fullPath -Force | Out-Null
Write-Host "Created registry key."
}
# Write UserEmail
Set-ItemProperty -Path $fullPath -Name "UserEmail" -Value $targetUPN -Type String -Force
if ($?) { Write-Host "Set UserEmail: OK" }
# Write OrganizationKey
Set-ItemProperty -Path $fullPath -Name "OrganizationKey" -Value $organizationKey -Type String -Force
if ($?) { Write-Host "Set OrganizationKey: OK" }
} catch {
Write-Error "Failed to set registry for $($app.Name): $($_.Exception.Message)"
# We continue to the next app even if one fails
}
}
Write-Host "Script execution finished successfully."
Stop-Transcript
exit 0