【问题标题】:How to write custom output to CSV from Powershell?如何从 Powershell 将自定义输出写入 CSV?
【发布时间】:2014-09-11 12:39:52
【问题描述】:

所以我是 PowerShell 的新手,我的任务是创建脚本以更好地管理我们环境中的用户帐户。我编写了以下脚本(可能非常糟糕),使非活动帐户过期,将它们移动到“禁用”OU,并吐出具有某些用户属性的 CSV。我想要做的是添加一行,如果脚本运行并且没有找到非活动帐户,则会在 CSV 中写入类似“未找到用户”的内容。到目前为止,谷歌搜索已被证明是徒劳的,因此任何输入都会有所帮助。谢谢!

#EXPIRES INACTIVE ACCOUNTS AND MOVES THEM TO DISABLED OU

#Today's Date
$today=get-date -uformat "%Y/%m/%d"

#Date to search by
$time=(get-date).AddDays(-730)

#Expiration date
$expire=(get-date).AddDays(-1)

#Set variable for accounts to expire
$users=Get-ADUser -SearchBase 'OU=myusers,DC=mydomain,DC=com' -filter   {(Passwordlastset -lt $time) -and (lastlogondate -lt $time)} |` 
? {$_.Distinguishedname -notlike '*OU=Disabled*'}

#Sets CSV Path
$csvFilePath="\\myfilepath\mylogs\Disabled $(get-date -f yyyy-MM-dd).csv"

$users | Foreach-object {get-ADUser -identity $_ -properties *} |select name, samaccountname, employeeid, Description |`
Export-Csv $csvFilePath -NoTypeInformation

#Changes Description to disabled - dateDisabled
$userDesc= "Disabled Inactive" + " - " + $today

$users | Set-ADUser -AccountExpirationDate $expire -Description $userdesc
$users | move-adobject -targetpath 'OU=Disabled,OU=myusers,DC=mydomain,DC=com'

【问题讨论】:

    标签: powershell csv scripting identity


    【解决方案1】:

    如果脚本是正常的,那么它就很好。你不应该需要改变很多东西。是的,代码可以提高效率,但最终结果仍然是一样的。

    对于您要问的内容,您只需要从 $users 获取计数,并在 $users = ... 行之后有一个 if 语句

    If ((Measure-Object -InputObject $users).Count -gt 0){
        #Process Code Here
    } Else {
         "No users found with criteria used." | Out-File -FilePath $csvFilePath -Append  
    }
    

    Measure-Object 将提供传递的输入对象的详细信息。在我们的例子中$users。 Measure-Object 可以返回多个值。我们只对.Count感兴趣

    【讨论】:

    • 感谢您的快速回复,这似乎正是我想要的。
    猜你喜欢
    • 2022-10-08
    • 1970-01-01
    • 2015-06-29
    • 2014-07-03
    • 2012-07-22
    • 1970-01-01
    • 1970-01-01
    • 2016-01-18
    • 1970-01-01
    相关资源
    最近更新 更多