0

How can I fix this problem? I'm trying to display powershell script output on a label. The PowerShell code working fine when I run it, but if I have to get the output to display nothing display only the error message what I write, If I change the script and put Write-Output(before get-aduser) and I run it 1601/01/01 00:00:00 this date appear 4x times(c# able to display this version)

Powershell code(display the password expiration date of the currently logged in user):

Get-ADUser -Filter "SamAccountName -eq '$env:username'" -Properties "msDS-UserPasswordExpiryTimeComputed" | 
Select-Object -Property @{Name="ExpiryDate";Expression={[datetime]::FromFileTime($_."msDS-UserPasswordExpiryTimeComputed")}} | ft ExpiryDate -HideTableHeaders

C#

    PowerShell ps = PowerShell.Create();
    ps.AddScript(File.ReadAllText(@"C:\temp\passexp.ps1"));
    ps.AddCommand("Out-String");
    var result = ps.Invoke();

    foreach (var item in result)
    {
        label5.Text = item.ToString();
    }
    if (ps.HadErrors==true)
    {
        label5.Text = "Error!";
    }
4

1 回答 1

0

我会更改您的 passexp.ps1 脚本,以同时考虑属性PasswordNeverExpiresPasswordNotRequired.
接下来,ps.AddCommand("Out-String");从 C# 代码中删除该行。

$properties = 'PasswordNeverExpires', 'PasswordNotRequired', 'msDS-UserPasswordExpiryTimeComputed'
$user = Get-ADUser -Filter "SamAccountName -eq '$env:USERNAME'" -Properties $properties

# do not output a date, but rather a message in these cases
if ($user.PasswordNeverExpires) { return "Password for user $($env:USERNAME) never expires"}
if ($user.PasswordNotRequired)  { return "User $($env:USERNAME) doesn't need a password"}

# return the password expiry date as object (local time)
[datetime]::FromFileTime($_."msDS-UserPasswordExpiryTimeComputed")
于 2021-12-30T12:22:20.400 回答