다음을 통해 공유


수정을 위한 PowerShell 스크립트

이 문서에는 고객이 직접 만드는 방법을 알아보기 위해 템플릿으로 구현하거나 사용할 수 있는 샘플 스크립트가 포함되어 있습니다. 여기에 제공된 정보를 사용하여 수정을 위한 스크립트 패키지를 만듭니 .

스크립트 설명

다음 표에서는 스크립트 이름, 설명, 검색, 수정 및 구성 가능한 항목을 보여 줍니다. 이름이 Detect로 시작하는 스크립트 파일은 검색 스크립트입니다. 수정 스크립트는 Remediate으로 시작합니다. 이러한 스크립트는 이 문서의 다음 섹션에서 복사할 수 있습니다.

스크립트 이름 설명
네트워크 인증서 확인
Detect_Expired_Issuer_Certificates.ps1
Remediate_Expired_Issuer_Certificates.ps1
컴퓨터 또는 사용자의 개인 저장소에서 만료되었거나 만료가 가까운 CA 발급 인증서를 검색합니다.
검색 스크립트에서 의 값을 $strMatch 변경하여 CA를 지정합니다. 만료된 인증서를 찾으려면 $expiringDays에 0을 지정하고, 만료가 가까운 인증서를 찾으려면 다른 일 수를 지정합니다.

사용자에게 알림 메시지를 표시하여 수정합니다.
$Title 사용자가 볼 메시지 제목과 텍스트를 사용하여 및 $msgText 값을 지정합니다.

갱신해야 할 수 있는 만료된 인증서를 사용자에게 알합니다.

로그온한 자격 증명을 사용하여 스크립트 실행: 예
부실 인증서 지우기
Detect_Expired_User_Certificates.ps1
Remediate_Expired_User_Certificates.ps1
현재 사용자의 개인 저장소에서 만료된 CA 발급 인증서를 검색합니다.
검색 스크립트에서 의 값을 $certCN 변경하여 CA를 지정합니다.

현재 사용자의 개인 저장소에서 CA에서 발급한 만료된 인증서를 삭제하여 수정합니다.
수정 스크립트에서 의 값을 $certCN 변경하여 CA를 지정합니다.

현재 사용자의 개인 저장소에서 CA에서 발급한 만료된 인증서를 찾아 삭제합니다.

로그온한 자격 증명을 사용하여 스크립트 실행: 예
부실 그룹 정책 업데이트 (기본 제공)
Detect_stale_Group_Policies.ps1
Remediate_stale_GroupPolicies.ps1
마지막 그룹 정책 새로 고침이 7 days보다 오래 되었는지 검색합니다.
이 스크립트 패키지는 수정에 포함되지만 임계값을 변경하려면 복사본이 제공됩니다. 검색 스크립트에서 $numDays 값을 변경하여 7일 임계값을 사용자 지정합니다.

를 실행 gpupdate /target:computer /force 하여 수정하고 gpupdate /target:user /force

그룹 정책을 통해 인증서 및 구성이 배달될 때 네트워크 연결 관련 지원 호출을 줄이는 데 도움이 될 수 있습니다.

로그온한 자격 증명을 사용하여 스크립트 실행: 예

네트워크 인증서 스크립트 패키지 확인

이 스크립트 패키지는 만료되었거나 거의 만료된 컴퓨터 또는 사용자의 개인 저장소에서 CA에서 발급한 인증서를 검색합니다. 스크립트는 사용자에게 알림 메시지를 발생시켜 수정합니다.

Detect_Expired_Issuer_Certificates.ps1

#=============================================================================================================================
#
# Script Name:     Detect_Expired_Issuer_Certificates.ps1
# Description:     Detect expired certificates issued by "CN=<your CA here>" in either Machine
#                  or User certificate store
# Notes:           Change the value of the variable $strMatch from "CN=<your CA here>" to "CN=..."
#                  For testing purposes the value of the variable $expiringDays can be changed to a positive integer
#                  Don't change the $results variable
#
#=============================================================================================================================

# Define Variables
$results = @()
$expiringDays = 0
$strMatch = "CN=<your CA here>"

try
{
    $results = @(Get-ChildItem -Path Cert:\LocalMachine\My -Recurse -ExpiringInDays $expiringDays | where {$_.Issuer -match $strMatch})
    $results += @(Get-ChildItem -Path Cert:\CurrentUser\My -Recurse -ExpiringInDays $expiringDays | where {$_.Issuer -match $strMatch}) 
    if (($results -ne $null)){
        #Below necessary for Intune as of 10/2019 will only remediate Exit Code 1
        Write-Host "Match"
        Return $results.count
        exit 1
    }
    else{
        #No matching certificates, do not remediate
        Write-Host "No_Match"        
        exit 0
    }   
}
catch{
    $errMsg = $_.Exception.Message
    Write-Error $errMsg
    exit 1
}

Remediate_Expired_Issuer_Certificates.ps1

#=============================================================================================================================
#
# Script Name:     Remediate_Expired_Issuer_Certificates.ps1
# Description:     Raise a Toast Notification if expired certificates issued by "CN=..."
#                  to user or machine on the machine where detection script found them. No remediation action besides
#                  the Toast is taken.
# Notes:           Change the values of the variables $Title and $msgText
#
#=============================================================================================================================

## Raise toast to have user contact whoever is specified in the $msgText

# Define Variables
$delExpCert = 0
$Title = "Title"
$msgText = "message"

# Main script
[Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] | Out-Null
[Windows.UI.Notifications.ToastNotification, Windows.UI.Notifications, ContentType = WindowsRuntime] | Out-Null
[Windows.Data.Xml.Dom.XmlDocument, Windows.Data.Xml.Dom.XmlDocument, ContentType = WindowsRuntime] | Out-Null

$APP_ID = '{1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\WindowsPowerShell\v1.0\powershell.exe'

$template = @"
<toast>
    <visual>
        <binding template="ToastText02">
            <text id="1">$Title</text>
            <text id="2">$msgText</text>
        </binding>
    </visual>
</toast>
"@

$xml = New-Object Windows.Data.Xml.Dom.XmlDocument
$xml.LoadXml($template)
$toast = New-Object Windows.UI.Notifications.ToastNotification $xml
[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier($APP_ID).Show($toast)

부실 인증서 스크립트 패키지 지우기

이 스크립트 패키지는 현재 사용자의 개인 저장소에서 만료된 CA 발급 인증서를 검색합니다. 이 스크립트는 현재 사용자의 개인 저장소에서 만료된 CA 발급 인증서를 삭제하여 수정합니다.

Detect_Expired_User_Certificates.ps1

#=============================================================================================================================
#
# Script Name:     Detect_Expired_User_Certificates.ps1
# Description:     Detect expired certificates issued by "CN=<your CA here>" to User
# Notes:           Change the value of the variable $certCN from "CN=<your CA here>" to "CN=...".
#                  Don't change $results
#
#=============================================================================================================================

# Define Variables
$results = 0
$certCN = "CN=<your CA here>"

try
{   
    $results = Get-ChildItem -Path Cert:\CurrentUser\My -Recurse -ExpiringInDays 0 | where {$_.Issuer -eq($certCN)}
    if (($results -ne $null)){
        #Below necessary for Intune as of 10/2019 will only remediate Exit Code 1
        Write-Host "Match"
        Return $results.count
        exit 1
    }
    else{
        Write-Host "No_Match"
        exit 0
    }    
}
catch{
    $errMsg = $_.Exception.Message
    Write-Error $errMsg
    exit 1
}

Remediate_Expired_User_Certificates.ps1

#=============================================================================================================================
#
# Script Name:     Remediate_Expired_User_Certificates.ps1
# Description:     Remove expired certificates issued by "CN=<your CA here>" to User
# Notes:           Change the value of the variable $certCN from "CN=<your CA here>" to "CN=..."
#
#=============================================================================================================================

# Define Variables
$certCN = "CN=<your CA here>"

try
{
    Get-ChildItem -Path cert:\CurrentUser -Recurse -ExpiringInDays 0 | where {$_.Issuer -eq($certCN)} | Remove-Item
    exit 0
}
catch{
    $errMsg = $_.Exception.Message
    Write-Error $errMsg
    exit 1
}

부실 그룹 정책 스크립트 패키지 업데이트

이 스크립트 패키지는 수정에 포함되지만 임계값을 변경하려면 복사본이 제공됩니다.

이 스크립트 패키지는 마지막 그룹 정책 새로 고침이 7 days보다 오래 되었는지 검색합니다. 스크립트는 gpupdate /target:computer /forcegpupdate /target:user /force을(를) 실행하여 수정합니다.

Detect_stale_Group_Policies.ps1

#=============================================================================================================================
#
# Script Name:     Detect_stale_Group_Policies.ps1
# Description:     Detect if Group Policy has been updated within number of days
# Notes:           Remediate if "Match", $lastGPUpdateDays default value of 7, change as appropriate
#
#=============================================================================================================================

# Define Variables

try {
    $gpResult = [datetime]::FromFileTime(([Int64] ((Get-ItemProperty -Path "Registry::HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\State\Machine\Extension-List\{00000000-0000-0000-0000-000000000000}").startTimeHi) -shl 32) -bor ((Get-ItemProperty -Path "Registry::HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\State\Machine\Extension-List\{00000000-0000-0000-0000-000000000000}").startTimeLo))
    $lastGPUpdateDate = Get-Date ($gpResult[0])
    [int]$lastGPUpdateDays = (New-TimeSpan -Start $lastGPUpdateDate -End (Get-Date)).Days
        
    if ($lastGPUpdateDays -gt 7){
        #Exit 1 for Intune. We want it to be within the last 7 days "Match" to remediate in SCCM
        Write-Host "Match"
        exit 1
    }
    else {
        #Exit 0 for Intune and "No_Match" for SCCM, only remediate "Match"
        Write-Host "No_Match"
        exit 0
    }
}
catch {
    $errMsg = $_.Exception.Message
    return $errMsg
    exit 1
}

Remediate_stale_GroupPolicies.ps1

#=============================================================================================================================
#
# Script Name:     Remediate_stale_GroupPolicies.ps1
# Description:     This script triggers Group Policy update
# Notes:           No variable substitution needed
#
#=============================================================================================================================

try {
    $compGPUpd = gpupdate /force
    $gpResult = [datetime]::FromFileTime(([Int64] ((Get-ItemProperty -Path "Registry::HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\State\Machine\Extension-List\{00000000-0000-0000-0000-000000000000}").startTimeHi) -shl 32) -bor ((Get-ItemProperty -Path "Registry::HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\State\Machine\Extension-List\{00000000-0000-0000-0000-000000000000}").startTimeLo))
    $lastGPUpdateDate = Get-Date ($gpResult[0])
    [int]$lastGPUpdateDays = (New-TimeSpan -Start $lastGPUpdateDate -End (Get-Date)).Days

    if ($lastGPUpdateDays -eq 0){
        Write-Host "gpupdate completed successfully"
        exit 0
    }
    else{
        Write-Host "gpupdate failed"
        }
}
catch{
    $errMsg = $_.Exception.Message
    return $errMsg
    exit 1
}

다음 단계

스크립트 패키지 배포에 대한 자세한 내용은 수정을 참조하세요.