LLI Wiki — My Digital Knowledge Base

PowerShell : lancer un script sous un autre compte avec un credential stocké

CredentialManager, Get-StoredCredential et Start-Process -Credential pour exécuter un script sans saisir de mot de passe.

Exécuter un script PowerShell sous un autre compte depuis un contexte planifié ou automatisé, sans saisir le mot de passe : stocker le credential une fois dans le Gestionnaire d'informations d'identification Windows, puis le passer à Start-Process -Credential.

Stocker le credential

Le module CredentialManager fournit New-StoredCredential et Get-StoredCredential.

Install-Module CredentialManager

# Prompt once for the account, then store it under a target name
Get-Credential -UserName "DOMAIN\svc_healthcheck" -Message "Health check" | New-StoredCredential -Target "healthcheck-target"

Le credential stocké n'est lisible que par l'utilisateur Windows qui l'a enregistré : exécuter cette étape avec le compte qui lancera ensuite le traitement.

Lancer un script avec le credential stocké

$cred = Get-StoredCredential -Target "healthcheck-target"
$powershellArguments = "-file D:\scripts\healthcheck.ps1"
Start-Process powershell.exe -ArgumentList $powershellArguments -Credential $cred

Les arguments du script s'ajoutent après le nom du fichier :

$powershellArguments = "-file D:\scripts\healthcheck.ps1", "arg1", "arg2"

Le script peut aussi être lu depuis un partage réseau :

$powershellArguments = "-file \\fileserver\share\healthcheck.ps1"
Start-Process powershell.exe -ArgumentList $powershellArguments -Credential $cred

Récupérer la sortie et le code de retour

# Redirect standard output to a file
Start-Process whoami -RedirectStandardOutput output.txt -Credential $cred

# Wait for the process and read its exit code
$process = Start-Process -FilePath ping -ArgumentList localhost -NoNewWindow -PassThru -Wait
$process.ExitCode

Remarques

Mastodon LLIMastodon SocialFosstodon