IQ started the topic Code for sending attachment as an email in PowerShell in
PowerShell Forum 1 year, 12 months ago
Hello All,
Can someone please post the working code for sending an attachment via email using Powershell. I have tried some online code, but I am unable to do so.
Thanks
IQ
IQ replied to the topic Unable to export to a Excel file or CSV with the PowerShell cmdlet Export-Csv in
PowerShell Forum 2 years ago
Excellent help, Leos. You are a real Pro, it works like a charm. Great help. Thank you so much.
IQ started the topic Unable to export to a Excel file or CSV with the PowerShell cmdlet Export-Csv in
PowerShell Forum 2 years ago
How to export the output of the Get-ADUser cmdlet to an Excel file? Excel-CSV is not showing the output as expected. It’s showing ASCII characters. On the other hand, if I use Out-File C:ADUsers.txt to generate a txt file it works fine. But I need to generate a CSV or an Excel file. How can I do this?
I am using Export-Csv -Path c:tempUserData.csv.
import-module activedirectory Get-ADUser -Filter * -Properties * | sort-object -property SamAccountName | Format-Table -property ` @{Name="Logon Name";Expression={$_.SamAccountName}}, @{Name="First Name";Expression={$_.givenName}}, @{Name="Initials";Expression={$_.Initials}}, @{Name="Last Logon";Expression={$_.LastLogonDate}}` -AutoSize | Out-File C:ADUsers.txt
IQ replied to the topic Write output to file within a PowerShell foreach loop in
PowerShell Forum 2 years ago
Hi David,
Since the code did not work, I have modified the way this could be done, my new code is given below,
however I cannot seem to see the output within the foreach statement, is there anything wrong I am doing hereImport-Module ActiveDirectory
#Set the number of days within expiration. This will start to send the email x number of days before it is expired.
$DaysWithinExpiration = 90#Set the days where the password is already expired and needs to change. — Do Not Modify —
$MaxPwdAge = (Get-ADDefaultDomainPasswordPolicy).MaxPasswordAge.Days
$expiredDate = (Get-Date).addDays(-$MaxPwdAge)#Set the number of days until you would like to begin notifing the users. — Do Not Modify —
$emailDate = (Get-Date).addDays(-($MaxPwdAge – $DaysWithinExpiration))#Filters for all users who’s password is within $date of expiration.
$ExpiredUsers = Get-ADUser -Filter {(PasswordLastSet -lt $emailDate) -and (PasswordLastSet -gt $expiredDate) -and (PasswordNeverExpires -eq $false) -and (Enabled -eq $true)} -Properties PasswordNeverExpires, PasswordLastSet, Mail -SearchBase “OU=Service Accounts,OU=SG1,OU=WAT,DC=cit,DC=ad,DC=cit,DC=cc” | select samaccountname, PasswordLastSet, @{name = “DaysUntilExpired”; Expression = {$_.PasswordLastSet – $ExpiredDate | select -ExpandProperty Days}}, @{name = “EmailAddress”; Expression = {$_.mail}} | Sort-Object PasswordLastSet
$ExpiredUsersForeach ($User in $ExpiredUsers) {
$Message = ‘User has a password expiration date ‘ + $ExpiredUsers.samaaccountname + $PasswordLastSet
Add-Content -Path C:TempPasswordExpList.txt -Value $MessageIQ replied to the topic Write output to file within a PowerShell foreach loop in
PowerShell Forum 2 years ago
PS C:Usersfquresh2> get-aduser -ldapfilter ‘(&(objectclass=user)(samaccountname=cpenic))’ -properties * | get-member TypeName: Microsoft.ActiveDirectory.Management.ADUser Name MemberType Definition ---- ---------- ---------- Contains Method bool Contains(string propertyName) Equals Method bool Equals(System.Object obj) GetEnumerator Method System.Collections.IDictionaryEnumerator GetEnumerator() GetHashCode Method int GetHashCode() GetType Method type GetType() ToString Method string ToString() Item ParameterizedProperty Microsoft.ActiveDirectory.Management.ADPropertyValueCollection Item(str... AccountExpirationDate Property System.DateTime AccountExpirationDate {get;set;} accountExpires Property System.Int64 accountExpires {get;set;} AccountLockoutTime Property System.DateTime AccountLockoutTime {get;set;} AccountNotDelegated Property System.Boolean AccountNotDelegated {get;set;} AllowReversiblePasswordEncryption Property System.Boolean AllowReversiblePasswordEncryption {get;set;} AuthenticationPolicy Property Microsoft.ActiveDirectory.Management.ADPropertyValueCollection Authenti... AuthenticationPolicySilo Property Microsoft.ActiveDirectory.Management.ADPropertyValueCollection Authenti... BadLogonCount Property System.Int32 BadLogonCount {get;} badPasswordTime Property System.Int64 badPasswordTime {get;set;} badPwdCount Property System.Int32 badPwdCount {get;set;} CannotChangePassword Property System.Boolean CannotChangePassword {get;set;} CanonicalName Property System.String CanonicalName {get;} Certificates Property Microsoft.ActiveDirectory.Management.ADPropertyValueCollection Certific... City Property System.String City {get;set;} CN Property System.String CN {get;} codePage Property System.Int32 codePage {get;set;} Company Property System.String Company {get;set;} CompoundIdentitySupported Property Microsoft.ActiveDirectory.Management.ADPropertyValueCollection Compound... Country Property System.String Country {get;set;} countryCode Property System.Int32 countryCode {get;set;} Created Property System.DateTime Created {get;} createTimeStamp Property System.DateTime createTimeStamp {get;} Deleted Property System.Boolean Deleted {get;} Department Property System.String Department {get;set;} Description Property System.String Description {get;set;} DisplayName Property System.String DisplayName {get;set;} DistinguishedName Property System.String DistinguishedName {get;set;} Division Property System.String Division {get;set;} DoesNotRequirePreAuth Property System.Boolean DoesNotRequirePreAuth {get;set;} dSCorePropagationData Property Microsoft.ActiveDirectory.Management.ADPropertyValueCollection dSCorePr... EmailAddress Property System.String EmailAddress {get;set;} EmployeeID Property System.String EmployeeID {get;set;} EmployeeNumber Property System.String EmployeeNumber {get;set;} Enabled Property System.Boolean Enabled {get;set;} extensionAttribute6 Property System.String extensionAttribute6 {get;set;} extensionAttribute7 Property System.String extensionAttribute7 {get;set;} Fax Property System.String Fax {get;set;} GivenName Property System.String GivenName {get;set;} HomeDirectory Property System.String HomeDirectory {get;set;} HomedirRequired Property System.Boolean HomedirRequired {get;set;} HomeDrive Property System.String HomeDrive {get;set;} HomePage Property System.String HomePage {get;set;} HomePhone Property System.String HomePhone {get;set;} Initials Property System.String Initials {get;set;} instanceType Property System.Int32 instanceType {get;} isDeleted Property System.Boolean isDeleted {get;} KerberosEncryptionType Property Microsoft.ActiveDirectory.Management.ADPropertyValueCollection Kerberos... l Property System.String l {get;set;} LastBadPasswordAttempt Property System.DateTime LastBadPasswordAttempt {get;} LastKnownParent Property System.String LastKnownParent {get;} lastLogon Property System.Int64 lastLogon {get;set;} LastLogonDate Property System.DateTime LastLogonDate {get;} lastLogonTimestamp Property System.Int64 lastLogonTimestamp {get;set;} LockedOut Property System.Boolean LockedOut {get;set;} lockoutTime Property System.Int64 lockoutTime {get;set;} logonCount Property System.Int32 logonCount {get;set;} LogonWorkstations Property System.String LogonWorkstations {get;set;} Manager Property System.String Manager {get;set;} MemberOf Property Microsoft.ActiveDirectory.Management.ADPropertyValueCollection MemberOf... MNSLogonAccount Property System.Boolean MNSLogonAccount {get;set;} MobilePhone Property System.String MobilePhone {get;set;} Modified Property System.DateTime Modified {get;} modifyTimeStamp Property System.DateTime modifyTimeStamp {get;} mS-DS-ConsistencyGuid Property System.Byte[] mS-DS-ConsistencyGuid {get;set;} msDS-User-Account-Control-Computed Property System.Int32 msDS-User-Account-Control-Computed {get;} msTSExpireDate Property System.DateTime msTSExpireDate {get;set;} msTSLicenseVersion Property System.String msTSLicenseVersion {get;set;} msTSLicenseVersion2 Property System.String msTSLicenseVersion2 {get;set;} msTSLicenseVersion3 Property System.String msTSLicenseVersion3 {get;set;} msTSManagingLS Property System.String msTSManagingLS {get;set;} Name Property System.String Name {get;} nTSecurityDescriptor Property System.DirectoryServices.ActiveDirectorySecurity nTSecurityDescriptor {... ObjectCategory Property System.String ObjectCategory {get;} ObjectClass Property System.String ObjectClass {get;set;} ObjectGUID Property System.Nullable`1[[System.Guid, mscorlib, Version=4.0.0.0, Culture=neut... objectSid Property System.Security.Principal.SecurityIdentifier objectSid {get;} Office Property System.String Office {get;set;} OfficePhone Property System.String OfficePhone {get;set;} Organization Property System.String Organization {get;set;} OtherName Property System.String OtherName {get;set;} PasswordExpired Property System.Boolean PasswordExpired {get;set;} PasswordLastSet Property System.DateTime PasswordLastSet {get;set;} PasswordNeverExpires Property System.Boolean PasswordNeverExpires {get;set;} PasswordNotRequired Property System.Boolean PasswordNotRequired {get;set;} physicalDeliveryOfficeName Property System.String physicalDeliveryOfficeName {get;set;} POBox Property System.String POBox {get;set;} PostalCode Property System.String PostalCode {get;set;} PrimaryGroup Property System.String PrimaryGroup {get;} primaryGroupID Property System.Int32 primaryGroupID {get;set;} PrincipalsAllowedToDelegateToAccount Property Microsoft.ActiveDirectory.Management.ADPropertyValueCollection Principa... ProfilePath Property System.String ProfilePath {get;set;} ProtectedFromAccidentalDeletion Property System.Boolean ProtectedFromAccidentalDeletion {get;set;} pwdLastSet Property System.Int64 pwdLastSet {get;set;} SamAccountName Property System.String SamAccountName {get;set;} sAMAccountType Property System.Int32 sAMAccountType {get;set;} ScriptPath Property System.String ScriptPath {get;set;} sDRightsEffective Property System.Int32 sDRightsEffective {get;} ServicePrincipalNames Property Microsoft.ActiveDirectory.Management.ADPropertyValueCollection ServiceP... SID Property System.Security.Principal.SecurityIdentifier SID {get;set;} SIDHistory Property Microsoft.ActiveDirectory.Management.ADPropertyValueCollection SIDHisto... SmartcardLogonRequired Property System.Boolean SmartcardLogonRequired {get;set;} sn Property System.String sn {get;set;} st Property System.String st {get;set;} State Property System.String State {get;set;} StreetAddress Property System.String StreetAddress {get;set;} Surname Property System.String Surname {get;set;} telephoneNumber Property System.String telephoneNumber {get;set;} Title Property System.String Title {get;set;} TrustedForDelegation Property System.Boolean TrustedForDelegation {get;set;} TrustedToAuthForDelegation Property System.Boolean TrustedToAuthForDelegation {get;set;} UseDESKeyOnly Property System.Boolean UseDESKeyOnly {get;set;} userAccountControl Property System.Int32 userAccountControl {get;set;} userCertificate Property Microsoft.ActiveDirectory.Management.ADPropertyValueCollection userCert... UserPrincipalName Property System.String UserPrincipalName {get;set;} uSNChanged Property System.Int64 uSNChanged {get;} uSNCreated Property System.Int64 uSNCreated {get;} whenChanged Property System.DateTime whenChanged {get;} whenCreated Property System.DateTime whenCreated {get;}
IQ replied to the topic Write output to file within a PowerShell foreach loop in
PowerShell Forum 2 years ago
Output of first command AccountExpirationDate : 12/31/2022 12:00:00 AM accountExpires : 133169364000000000 AccountLockoutTime : AccountNotDelegated : False AllowReversiblePasswordEncryption : False AuthenticationPolicy : {} AuthenticationPolicySilo : {} BadLogonCount : 1 badPasswordTime : 132394676544574602 badPwdCount : 1 CannotChangePassword : False CanonicalName : tw.ad.city.ca/WAT/SG1/Users/cpenic Certificates : {} City : city CN : cpenic codePage : 0 Company : CompoundIdentitySupported : {} Country : countryCode : 0 Created : 03/02/2017 10:39:59 AM createTimeStamp : 03/02/2017 10:39:59 AM Deleted : Department : cw Description : Enabled as per RMT0144973 - 01/09/2020 - HA DisplayName : Christopher Penic DistinguishedName : CN=cpenic,OU=Users,OU=SG1,OU=WAT,DC=tw,DC=ad,DC=city,DC=ca Division : SG1 DoesNotRequirePreAuth : False dSCorePropagationData : {07/13/2020 9:54:41 AM, 07/13/2020 9:51:30 AM, 03/21/2020 9:24:37 AM, 03/06/2020 2:32:14 PM...} EmailAddress : EmployeeID : EmployeeNumber : Enabled : True extensionAttribute6 : SG1 extensionAttribute7 : NONSTAFF Fax : GivenName : Christopher HomeDirectory : HomedirRequired : False HomeDrive : HomePage : HomePhone : Initials : instanceType : 4 isDeleted : KerberosEncryptionType : {} l : city LastBadPasswordAttempt : 07/17/2020 9:54:14 AM LastKnownParent : lastLogon : 132231645411166084 LastLogonDate : 07/13/2020 12:08:45 PM lastLogonTimestamp : 132391301252011332 LockedOut : False lockoutTime : 0 logonCount : 1 LogonWorkstations : Manager : MemberOf : {CN=INTCA_UserCert_AutoEnrollment_TW,OU=COTInternalCA,OU=AD Specific,OU=Groups,OU=Service Accounts,DC=tw,DC=ad,DC=city,DC=ca, CN=CTX_CMS_Users_PROD,OU=PROD,OU=Citrix Groups,OU=Groups,OU=SG1,OU=WAT,DC=tw,DC=ad,DC=city,DC=ca, CN=CTX_External_Users_PROD,OU=PROD,OU=Citrix Groups,OU=Groups,OU=SG1,OU=WAT,DC=tw,DC=ad,DC=city,DC=ca} MNSLogonAccount : False MobilePhone : Modified : 07/13/2020 12:09:56 PM modifyTimeStamp : 07/13/2020 12:09:56 PM mS-DS-ConsistencyGuid : {113, 206, 214, 51...} msDS-User-Account-Control-Computed : 0 msTSExpireDate : 09/11/2020 1:08:55 PM msTSLicenseVersion : 655360 msTSLicenseVersion2 : 7 msTSLicenseVersion3 : C50-10.00-S msTSManagingLS : 00377-60000-31895-AT945 Name : cpenic nTSecurityDescriptor : System.DirectoryServices.ActiveDirectorySecurity ObjectCategory : CN=Person,CN=Schema,CN=Configuration,DC=ad,DC=city,DC=ca ObjectClass : user ObjectGUID : 33d6ce71-e9da-4255-bbe9-3d3788fd1e8b objectSid : S-1-5-21-4230492499-2346530856-2212554079-36718 Office : 550 Bowes Road OfficePhone : 416-678-5493 Organization : OtherName : PasswordExpired : False PasswordLastSet : 07/13/2020 12:08:17 PM PasswordNeverExpires : False PasswordNotRequired : False physicalDeliveryOfficeName : 550 Bowes Road POBox : PostalCode : PrimaryGroup : CN=Domain Users,CN=Users,DC=wt,DC=ad,DC=city,DC=ca primaryGroupID : 513 PrincipalsAllowedToDelegateToAccount : {} ProfilePath : ProtectedFromAccidentalDeletion : False pwdLastSet : 132391300973390191 SamAccountName : cpenic sAMAccountType : 805306368 ScriptPath : sDRightsEffective : 0 ServicePrincipalNames : {} SID : S-1-5-21-4230492499-2346530856-2212554079-36718 SIDHistory : {} SmartcardLogonRequired : False sn : Penic st : Ontario State : Ontario StreetAddress : Surname : Penic telephonAccountExpirationDate : 12/31/2022 12:00:00 AM accountExpires : 133169364000000000 AccountLockoutTime : AccountNotDelegated : False AllowReversiblePasswordEncryption : False AuthenticationPolicy : {} AuthenticationPolicySilo : {} BadLogonCount : 1 badPasswordTime : 132394676544574602 badPwdCount : 1 CannotChangePassword : False CanonicalName : tw.ad.city.ca/WAT/SG1/Users/cpenic Certificates : {} City : city CN : cpenic codePage : 0 Company : CompoundIdentitySupported : {} Country : countryCode : 0 Created : 03/02/2017 10:39:59 AM createTimeStamp : 03/02/2017 10:39:59 AM Deleted : Department : cw Description : Enabled as per RMT0144973 - 01/09/2020 - HA DisplayName : Christopher Penic DistinguishedName : CN=cpenic,OU=Users,OU=SG1,OU=WAT,DC=tw,DC=ad,DC=city,DC=ca Division : SG1 DoesNotRequirePreAuth : False dSCorePropagationData : {07/13/2020 9:54:41 AM, 07/13/2020 9:51:30 AM, 03/21/2020 9:24:37 AM, 03/06/2020 2:32:14 PM...} EmailAddress : EmployeeID : EmployeeNumber : Enabled : True extensionAttribute6 : SG1 extensionAttribute7 : NONSTAFF Fax : GivenName : Christopher HomeDirectory : HomedirRequired : False HomeDrive : HomePage : HomePhone : Initials : instanceType : 4 isDeleted : KerberosEncryptionType : {} l : city LastBadPasswordAttempt : 07/17/2020 9:54:14 AM LastKnownParent : lastLogon : 132231645411166084 LastLogonDate : 07/13/2020 12:08:45 PM lastLogonTimestamp : 132391301252011332 LockedOut : False lockoutTime : 0 logonCount : 1 LogonWorkstations : Manager : MemberOf : {CN=INTCA_UserCert_AutoEnrollment_TW,OU=COTInternalCA,OU=AD Specific,OU=Groups,OU=Service Accounts,DC=tw,DC=ad,DC=city,DC=ca, CN=CTX_CMS_Users_PROD,OU=PROD,OU=Citrix Groups,OU=Groups,OU=SG1,OU=WAT,DC=tw,DC=ad,DC=city,DC=ca, CN=CTX_External_Users_PROD,OU=PROD,OU=Citrix Groups,OU=Groups,OU=SG1,OU=WAT,DC=tw,DC=ad,DC=city,DC=ca} MNSLogonAccount : False MobilePhone : Modified : 07/13/2020 12:09:56 PM modifyTimeStamp : 07/13/2020 12:09:56 PM mS-DS-ConsistencyGuid : {113, 206, 214, 51...} msDS-User-Account-Control-Computed : 0 msTSExpireDate : 09/11/2020 1:08:55 PM msTSLicenseVersion : 655360 msTSLicenseVersion2 : 7 msTSLicenseVersion3 : C50-10.00-S msTSManagingLS : 00377-60000-31895-AT945 Name : cpenic nTSecurityDescriptor : System.DirectoryServices.ActiveDirectorySecurity ObjectCategory : CN=Person,CN=Schema,CN=Configuration,DC=ad,DC=city,DC=ca ObjectClass : user ObjectGUID : 33d6ce71-e9da-4255-bbe9-3d3788fd1e8b objectSid : S-1-5-21-4230492499-2346530856-2212554079-36718 Office : 550 Bowes Road OfficePhone : 416-678-5493 Organization : OtherName : PasswordExpired : False PasswordLastSet : 07/13/2020 12:08:17 PM PasswordNeverExpires : False PasswordNotRequired : False physicalDeliveryOfficeName : 550 Bowes Road POBox : PostalCode : PrimaryGroup : CN=Domain Users,CN=Users,DC=wt,DC=ad,DC=city,DC=ca primaryGroupID : 513 PrincipalsAllowedToDelegateToAccount : {} ProfilePath : ProtectedFromAccidentalDeletion : False pwdLastSet : 132391300973390191 SamAccountName : cpenic sAMAccountType : 805306368 ScriptPath : sDRightsEffective : 0 ServicePrincipalNames : {} SID : S-1-5-21-4230492499-2346530856-2212554079-36718 SIDHistory : {} SmartcardLogonRequired : False sn : Penic st : Ontario State : Ontario StreetAddress : Surname : Penic telephoneNumber : 416-678-5493 Title : Project Manager TrustedForDelegation : False TrustedToAuthForDelegation : False UseDESKeyOnly : False userAccountControl : 512 userCertificate : {} UserPrincipalName : cpenic@citi.com uSNChanged : 48093793 uSNCreated : 119139 whenChanged : 07/13/2020 12:09:56 PM whenCreated : 03/02/2017 10:39:59 AMeNumber : 416-678-5493 Title : Project Manager TrustedForDelegation : False TrustedToAuthForDelegation : False UseDESKeyOnly : False userAccountControl : 512 userCertificate : {} UserPrincipalName : cpenic@citi.com uSNChanged : 48093793 uSNCreated : 119139 whenChanged : 07/13/2020 12:09:56 PM whenCreated : 03/02/2017 10:39:59 AM
IQ replied to the topic Write output to file within a PowerShell foreach loop in
PowerShell Forum 2 years ago
Hi David,
How do I get the full property list ? Also what do you mean by “sanitized is fine” ?
Thanks
IQ
IQ replied to the topic Write output to file within a PowerShell foreach loop in
PowerShell Forum 2 years ago
Hi David,Thanks for your reply, how can I fix this error ?
Also For one of the accounts the properties are shown below as you requested
AccountExpirationDate : 12/31/2022 12:00:00 AM
DistinguishedName : CN=cpenic,OU=Users,OU=SG1,OU=www,DC=wt,DC=ad,DC=cit,DC=cc
Enabled : True
GivenName : Christopher
Name : cpenic
ObjectClass : user
ObjectGUID : 33d6ce71-e9da-4255-bbe9-3d3788fd1e8b
SamAccountName : cpenic
SID : S-1-5-21-4230492499-2346530856-2212554079-36718
Surname : Penic
UserPrincipalName : cpenic@cit.cc
PropertyNames : {AccountExpirationDate, DistinguishedName, Enabled, GivenName…}
AddedProperties : {}
RemovedProperties : {}
ModifiedProperties : {}
PropertyCount : 11IQ replied to the topic Write output to file within a PowerShell foreach loop in
PowerShell Forum 2 years ago
I have modified the code to look like this but I am getting errors , Code I am using is below the errors.
Cannot convert argument "fileTime", with value: "12/25/2021 12:00:00 AM", for "FromFileTime" to type "System.Int64": "Cannot convert value "12/25/2021 12:00:00 AM" to type "System.Int64". Error: "Invalid cast from 'DateTime' to 'Int64'."" At C:Usersfquresh2DesktopPower_Shell_Script_For Expired_accountsfaiz_op.ps1:48 char:5 + $PasswordExp = [datetime]::parse([datetime]::FromFileTime($user.A ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodException + FullyQualifiedErrorId : MethodArgumentConversionInvalidCastArgument Cannot convert argument "fileTime", with value: "12/01/2019 12:00:00 AM", for "FromFileTime" to type "System.Int64": "Cannot convert value "12/01/2019 12:00:00 AM" to type "System.Int64". Error: "Invalid cast from 'DateTime' to 'Int64'."" At C:Usersfquresh2DesktopPower_Shell_Script_For Expired_accountsfaiz_op.ps1:48 char:5 + $PasswordExp = [datetime]::parse([datetime]::FromFileTime($user.A ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodException + FullyQualifiedErrorId : MethodArgumentConversionInvalidCastArgument Cannot convert argument "fileTime", with value: "12/01/2019 12:00:00 AM", for "FromFileTime" to type "System.Int64": "Cannot convert value "12/01/2019 12:00:00 AM" to type "System.Int64". Error: "Invalid cast from 'DateTime' to 'Int64'."" At C:Usersfquresh2DesktopPower_Shell_Script_For Expired_accountsfaiz_op.ps1:48 char:5 + $PasswordExp = [datetime]::parse([datetime]::FromFileTime($user.A ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodException + FullyQualifiedErrorId : MethodArgumentConversionInvalidCastArgument
—————————————–
Code I am using is shown below
———————————-
# sort-object -property ‘PwdLastSet’
#$PasswordExp = $users.PasswordLastSet.Addyears(1) I don’t think this is really what you are looking for; adding a year means they will never match
#$MailParams = @{
# To = $users.name
# From = ‘Faiz.Qureshi@mail.toronto.ca’
# SMTPServer = ‘mail.toronto.ca’
# Subject = ‘Password Expiration warning’
#}#$AdminMailParams = @{
# To = ‘iq@mail.cc’
# From = ‘iq@mail.cc’
# SMTPServer = ‘mail.cc’
# Subject = ‘Password Expiration warning list’
# Attachments = ‘C:TempPasswordExpList.txt’
#}foreach ($user in $Users) {
#Thinking about this part – because you are using -eq comparisons, this setup forcibly returns the midnight stamp, just like the initial warning variables do;
#otherwise, you’re dealing with 100 nanosecond ticks, and that would be virtually impossible to be equal
#I’m also assuming you are defining the Email stubs somewhere else
$PasswordExp = [datetime]::parse([datetime]::FromFileTime($user.AccountExpirationDate).ToString(‘yyyy-MM-dd’))
$username = $user.name
$Message = ‘User ({0}) has a password expiration date of {0}’ -f $username, $PasswordExp.ToLongDateString()
Add-Content -Path C:TempPasswordExpList.txt -Value $Messageswitch ($PasswordExp) {
($PasswordExp -eq $OneDayWarnDate) {
$WarningDays = ‘1’
$WarningDate = $OneDayWarnDate
# You are overwriting your own variable here with the $file statements, this does not make sense?
$VerboseMessage = ‘The password expiration for user {0} is within the OneDayWarnBlock’ -f $AccountExpirationDate
break
}
($PasswordExp -eq $SevenWarnDate) {
$WarningDays = ‘7’
$WarningDate = $SevenDayWarnDate
$VerboseMessage = ‘The password expiration for user {0} is within the SevenDayWarnBlock’ -f $AccountExpirationDate
break
}
($PasswordExp -eq $FifteenDayWarnDate) {
$WarningDays = ’15’
$WarningDate = $FifteenDayWarnDate
$VerboseMessage = ‘The password expiration for user {0} is within the FifteenDayWarnBlock’ -f $AccountExpirationDate
break
}
($PasswordExp -eq $ThirtyDayWarnDate) {
$WarningDays = ’30’
$WarningDate = $ThirtyDayWarnDate
$VerboseMessage = ‘The password expiration for user {0} is within the ThirtyDayWarnBlock’ -f $AccountExpirationDate
break
}
}}
# Write-Verbose -Message $VerboseMessage
# $MailParams.Add(‘Body’, ($EmailStub1, $users.name, $EmailStub2, $WarningDays, $EmailStub3, $WarningDate.ToString(‘yyyy-MM-dd’), $EmailStub4 -join ‘ ‘)) )
# Send-MailMessage $MailParams#Send-MailMessage @AdminMailParams
IQ replied to the topic Write output to file within a PowerShell foreach loop in
PowerShell Forum 2 years ago
Hi David,
If I use this command I am seeing the passwd last set values under AccountExprationDate , what is the difference between this and the previous command. Also is there a way I can substitute the nulls in AccountExprationDate with a sysdate ?
Get-ADUser -Filter ‘enabled -eq $true’ -Properties AccountExpirationDate |
Select sAMAccountName, distinguishedName, AccountExpirationDateIQ replied to the topic Write output to file within a PowerShell foreach loop in
PowerShell Forum 2 years, 1 month ago
Hi David,
I was able to fix the issue I had described in my reply and the code is now working, I am able to output username , PwdLastSet values to the output file, I will look into the email stub part later.
I have a problem though, looks like the PwdLastSet column is always null as they have not stored this information, as I mentioned earlier, I was using PwdLastSet and adding a year to it to get the password expiry date information as our AD was not letting us retrieve this information , so is there any other way for me to get the password expiry information ?
Thanks
IQ
IQ replied to the topic Write output to file within a PowerShell foreach loop in
PowerShell Forum 2 years, 1 month ago
Thanks David, for taking time to look into this piece of code for me.
Please ignore the $File pieces in the code , I was just playing with the syntax to familiarise myself.
With regards to PassWdEXp being one year + PasswordLastSet , we are using this as our AD prevents us from querying for Password expired info. and as a rule all our passwords are set to expire one year from the time they were last set. So to get PasswdExp we are adding one year to PasswordLastSet
I have tried to run your modified code but I am getting the error at line 13 of the code as shown below, Attached is the code as an attachment, please note I have commented the email stub portion of the code for now as I am only focussing on generating an output file for now.
Get-ADUser : Error parsing query: '{ Enabled -eq $True -and PasswordLastSet -gt 0 }' Error Message: 'syntax error' at position: '1'. At C:UsersDesktopPower_Shell_Script_For Expired_accountstst_op.ps1:13 char:10 + $users = Get-ADUser @GetADParams | + ~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ParserError: (:) [Get-ADUser], ADFilterParsingException + FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADFilterParsingException,Microsoft.ActiveDi rectory.Management.Commands.GetADUser
Line 13 of the code is
$users = Get-ADUser @GetADParams | Select-Object -Property 'Name', 'PwdLastSet' | sort-object -property 'PwdLastSet'
IQ replied to the topic Write output to file within a PowerShell foreach loop in
PowerShell Forum 2 years, 1 month ago
Hello David,
Thanks for your suggestions, I have tried to use this code as shown below to output the message to a file based on the number of days to expiry of the password, but somehow I think I am still missing something, I dont see any output getting generated. Where could I be going wrong ? Thanks for your help.
IQ
——————————————————–
$SevenWarnDate = (get-date).adddays(7).ToLongDateString() $OneDayWarnDate = (get-date).adddays(1).ToLongDateString() #Find accounts that are enabled and have expiring passwords $users = Get-ADUser -filter {Enabled -eq $True -and PasswordLastSet -gt 0 } ` -SearchBase "OU=Service Accounts,OU=SG1,OU=WAT,DC=wt,DC=ad,DC=cit,DC=cc" ` -Properties "Name", PasswordLastSet | Select-Object -Property "Name", "PasswordLastSet" |` sort-object -property PasswordLastSet $PasswordExp = $users.PasswordLastSet.Addyears(1) $MailParams = @{ To = $users.name From = 'iq@mail.cit.cc' SMTPServer = 'mail.cit.cc' #$SMTPServer Subject = 'Test' #$Subject } switch ($PasswordExp) { ($PasswordExp -eq $OneDayWarnDate) { $null = $MailParams.Add('Body', ( Body = ($EmailStub1, $users.name, $EmailStub2, $days, $EmailStub3, $SevenDayWarnDate, $EmailStub4 -join ' '))) $file = get-content test.txt -Raw $file = get-content test.txt set-content -Path test.txt -value $file get-content test.txt break } ($PasswordExp -eq $SevenWarnDate) { $null = $MailParams.Add('Body', ( Body = ($EmailStub1, $users.name, $EmailStub2, $days, $EmailStub3, $ThreeDayWarnDate, $EmailStub4 -join ' '))) $file = get-content test.txt -Raw $file = get-content test.txt set-content -Path test.txt -value $file get-content test.txt break break } ($PasswordExp -eq $FifteenDayWarnDate) { $null = $MailParams.Add('Body', ( Body = ($EmailStub1, $users.name, $EmailStub2, $days, $EmailStub3, $OneDayWarnDate, $EmailStub4 -join ' '))) $file = get-content test.txt -Raw $file = get-content test.txt set-content -Path test.txt -value $file get-content test.txt break } ($PasswordExp -eq $ThirtyDayWarnDate) { $null = $MailParams.Add('Body', ( Body = ($EmailStub1, $users.name, $EmailStub2, $days, $EmailStub3, $OneDayWarnDate, $EmailStub4 -join ' '))) $file = get-content test.txt -Raw $file = get-content test.txt set-content -Path test.txt -value $file get-content test.txt break } }
IQ replied to the topic Write output to file within a PowerShell foreach loop in
PowerShell Forum 2 years, 1 month ago
I have tried using Set-Content -Path C:test.txt -Value ‘foo’ to write the output to a file basically I need the UserId, PasswordExp written to the test file. This did not work, Is there a different command to be used to write to a file ?
Please let me know.
Thanks
IQ
IQ started the topic Write output to file within a PowerShell foreach loop in
PowerShell Forum 2 years, 1 month ago
Hello,
I am trying to modify the following PowerShell code to write to a file within the foreach loop’s if statement. So instead of Send-MailMessage -To $user.EmailAddress -From $MailSender -SmtpServer $SMTPServer -Subject $Subject `
-Body $EmailBodyI would like to write to a file, later this file will be emailed to the Domain Admins.
Please let me know how I can output the Send Mail message line of code into a file .
#Import AD Module Import-Module ActiveDirectory #Create warning dates for future password expiration $ThirtyDayWarnDate = (get-date).adddays(30).ToLongDateString() $FifteenDayWarnDate = (get-date).adddays(15).ToLongDateString() $SevenWarnDate = (get-date).adddays(7).ToLongDateString() $OneDayWarnDate = (get-date).adddays(1).ToLongDateString() #Find accounts that are enabled and have expiring passwords $users = Get-ADUser -filter {Enabled -eq $True -and PasswordLastSet -gt 0 } ` -SearchBase "OU=Service Accounts,OU=SG1,OU=WAT,DC=wt,DC=ad,DC=ed,DC=cn" ` -Properties "Name", PasswordLastSet | Select-Object -Property "Name", "PasswordLastSet" |` sort-object -property PasswordLastSet $PasswordExp = $users.PasswordLastSet.Addyears(1) foreach ($user in $users) { if ($PasswordExp -eq $OneDayWarnDate) { $days = 1 $EmailBody = $EmailStub1, $user.name, $EmailStub2, $days, $EmailStub3, $SevenDayWarnDate, $EmailStub4 -join ' ' Send-MailMessage -To $user.EmailAddress -From $MailSender -SmtpServer $SMTPServer -Subject $Subject -Body $EmailBody } elseif ($PasswordExp -eq $SevenWarnDate) { $days = 7 $EmailBody = $EmailStub1, $user.name, $EmailStub2, $days, $EmailStub3, $ThreeDayWarnDate, $EmailStub4 -join ' ' Send-MailMessage -To $user.EmailAddress -From $MailSender -SmtpServer $SMTPServer -Subject $Subject ` -Body $EmailBody } elseif ($PasswordExp -eq $FifteenDayWarnDate) { $days = 15 $EmailBody = $EmailStub1, $user.name, $EmailStub2, $days, $EmailStub3, $OneDayWarnDate, $EmailStub4 -join ' ' Send-MailMessage -To $user.EmailAddress -From $MailSender -SmtpServer $SMTPServer -Subject $Subject -Body $EmailBody } elseif ($PasswordExp -eq $ThirtyDayWarnDate) { $days = 30 $EmailBody = $EmailStub1, $user.name, $EmailStub2, $days, $EmailStub3, $OneDayWarnDate, $EmailStub4 -join ' ' Send-MailMessage -To $user.EmailAddress -From $MailSender -SmtpServer $SMTPServer -Subject $Subject -Body $EmailBody } else {} }
IQ replied to the topic Unable to retrieve full list of AD users with PowerShell in
PowerShell Forum 2 years, 1 month ago
Hi Leos,
We are having some trouble connecting to our mail server, so we would like to first develop this pseudo code and later integrate it with email server
Get Service_Account_List Order by PasswordExpireDate Decending Loop Service_Account in Service_Account List Is Expire_Date < 1 ? Message := Service_Account + "Account Password Expired"** Else Is Expire_Date <= 7?** Message := Service_Account + "Account Password Will Expire within in 7 Days"** Else Is Expire_Date <= 15?** Message := Service_Account + "Account Password Will Expire within in 15 Days"** Else Is Expire_Date <= 30?** Message := Service_Account + "Account Password Will Expire within in 30 Days" End Is Store Message in file End Loop
What is the best way to do this basically put all Accounts with the criteria given in a file and then loop through that file ?
IQ replied to the topic Unable to retrieve full list of AD users with PowerShell in
PowerShell Forum 2 years, 1 month ago
Thanks everyone for your suggestions. Looks like the requirements are changed for what we are trying to do here. I value your suggestions and your time to reply back.
Let me post what we are trying to do again
I am using the following script to get a list of all AD users
Get-ADUser -filter {Enabled -eq $True -and PasswordNeverExpires -eq $False} –Properties "DisplayName", "msDS-UserPasswordExpiryTimeComputed" | Select-Object -Property "Displayname",@{Name="ExpiryDate";Expression={[datetime]::FromFileTime($_."msDS-UserPasswordExpiryTimeComputed")}}| Export-CSV -Path ADUsers.csv
Using the users in the ADUSer.csv file (which is obtained using above code) , we would like to use the following pseudo code,
Get Service_Account_List Order by PasswordExpireDate Decending Loop Service_Account in Service_Account List Is Expire_Date < 1 ? Message := Service_Account + "Account Password Expired"** Else Is Expire_Date <= 7?** Message := Service_Account + "Account Password Will Expire within in 7 Days"** Else Is Expire_Date <= 15?** Message := Service_Account + "Account Password Will Expire within in 15 Days"** Else Is Expire_Date <= 30?** Message := Service_Account + "Account Password Will Expire within in 30 Days" End Is Store Message in file End Loop
Needed some help is building this pesudo code shown above, I am also going through tutorials and material which helps me translate this pesudo code into real code but since Powershell scripting is new to me, I am finding it a bit diificult. Any help will be highly appreciated.
IQ started the topic Unable to retrieve full list of AD users with PowerShell in
PowerShell Forum 2 years, 1 month ago
Hi,
I am using the following Get-ADUser cmdlet to retrieve the list of all AD users and output these to a file but this list is retrieving only 5 or 6 users, even though the number of active AD users is around 10,000. Where could I be going wrong ? Please advise.
Get-ADUser -filter {Enabled -eq $True -and PasswordNeverExpires -eq $False -and PasswordLastSet -gt 0 } ` -SearchBase "OU=Service Accounts,OU=SG1,OU=WAT,DC=wt,DC=ad,DC=city,DC=aa" ` -Properties Name, msDS-UserPasswordExpiryTimeComputed | Select-Object ` -Property Name, @{Name="PasswordExpiry";Expression={[datetime]::FromFileTime($_."msDS-UserPasswordExpiryTimeComputed")}} |` sort-object -property PasswordExpiry | ` Export-Csv -Path ./Password_Expiration.csv -NoType
IQ replied to the topic PowerShell script required to automate sending of emails with expired passwords in
PowerShell Forum 2 years, 1 month ago
Tried the script suggested in the post but I am getting an error
Get-ADUser : The search filter cannot be recognized
At line:21 char:1
+ Get-ADUser -LDAPFilter $LDAP | ForEach-Object {
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Get-ADUser], ADException
+ FullyQualifiedErrorId : ActiveDirectoryServer:8254,Microsoft.ActiveDirectory.Management.Commands.GetADUserIQ replied to the topic PowerShell script required to automate sending of emails with expired passwords in
PowerShell Forum 2 years, 1 month ago
thanks for your suggestions, will try this code to make it work on Windows 2016/Windows 10. For now I am just trying to write the soon to be expiring accounts in a file and then use SMTP to send an email, this needs to be automated using a Powershell script. Will let u know how it goes, thanks for your suggestion.
- Load More