プリンターのアクセス許可を変更したい。

Copper Contributor

https://social.technet.microsoft.com/Forums/ja-JP/4e01029e-8591-4e1c-ae35-e91e59448d5d/powershell124...

↑このサイトの中にあるコマンドレットを参考に、全プリンターの”Everyone”のアクセス許可を行いたい。

 

Get-Printer | Select-Object Name

のコマンドレットを使用して、プリンター名を取得することはできました。

 

しかし、取得したリストを"foreach"を使って1行づづ利用しようとすると、NULLとなってしまう。

この問題を解決したいので、助けで下さい。

 

エラーが発生したコードは以下です。

#PS1の実行ディレクトリを取得
$scriptPath = $MyInvocation.MyCommand.Path
$Directory = Split-Path -Parent $scriptPath

#インストール済みプリンター一覧の出力先パスを設定
$EPPath = $Directory + "\PrinterList.csv"

#プリンター名を取得し出力する。
Get-Printer | Select-Object Name| Export-Csv -Encoding Default -NoTypeInformation -Path $EPPath

$PrinterList = Import-Csv -Path $EPPath

#取得したプリンターリストから1行づつプリンター名を取得して権限変更を実行
foreach($PName in $PrinterList)
{
$user = "everyone" # 対象ユーザー名
$printerName = $PName # 対象プリンタ名

$printer = Get-WmiObject -Class win32_printer |
Where-Object {$_.Name -eq $printerName}

# プリンタのSecurity Descriptorを取得する
$sd = $printer.GetSecurityDescriptor().Descriptor

# DACLから$user以外のACEを取得する
$aces = @($sd.DACL |
Where-Object {$_.Trustee.Name -ne $user})

# ACEオブジェクトを生成する関数
# see: https://docs.microsoft.com/ja-jp/windows/desktop/CIMWin32Prov/setsecuritydescriptor-method-in-class-...
function createAce
{
param([string]$user, [int]$accessMask, [int]$type, [int]$flags)

$ace = ([WMIClass] "Win32_Ace").CreateInstance()
$Trustee = ([WMIClass] "Win32_Trustee").CreateInstance()
$SID = (new-object security.principal.ntaccount $user).translate([security.principal.securityidentifier])
[byte[]] $SIDArray = ,0 * $SID.BinaryLength
$SID.GetBinaryForm($SIDArray,0)
$Trustee.Name = $user
$Trustee.SID = $SIDArray
$ace.AccessMask = $accessMask
$ace.AceType = $type
$ace.AceFlags = $flags
$ace.Trustee = $Trustee
return $ace
}
# $user以外のACEと新しく作った$userのACEを結合
$aces +=
@(createAce -user $user -accessMask 983052 -type 0 -flags 0) + # ManagePrinters
@(createAce -user $user -accessMask 983088 -type 0 -flags 9) # ManageDocuments

$sd.DACL = [System.Management.ManagementBaseObject[]]$aces # DACLを更新
$printer.psbase.Scope.Options.EnablePrivileges = $true # 上書き許可
$ret = $printer.SetSecurityDescriptor($sd).ReturnValue # Security Descriptorを更新

if($ret -eq 0)
{
Write-Host "${user}の${printerName}に対するアクセス権を更新しました。"
}
else
{
Write-Host "アクセス権更新に失敗しました。"
}
}

 

0 Replies