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!";
    }
Tamás
  • 25
  • 4
  • The implication is that `$_."msDS-UserPasswordExpiryTimeComputed"` evaluates to either `$null` or the empty string. In principle, you can simplify your pipeline to `Get-ADUser -Filter "SamAccountName -eq '$env:username'" -Properties "msDS-UserPasswordExpiryTimeComputed" | ForEach-Object { [datetime]::FromFileTime($_."msDS-UserPasswordExpiryTimeComputed") }` - then you won't need `Out-String`. – mklement0 Dec 27 '21 at 17:43

1 Answers1

0

I would change your passexp.ps1 script to also consider the values for attributes PasswordNeverExpires and PasswordNotRequired.
Next, remove the line ps.AddCommand("Out-String"); from your C# code.

$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")
Theo
  • 57,719
  • 8
  • 24
  • 41