如何从Powershell将自定义输出写入CSV?

如何从Powershell将自定义输出写入CSV?,powershell,csv,scripting,identity,Powershell,Csv,Scripting,Identity,因此,我是PowerShell的新手,一直负责创建脚本,以便更好地管理我们环境中的用户帐户。我编写了下面的脚本(可能非常糟糕),它使非活动帐户过期,将它们移动到“已禁用”的OU,并输出具有特定用户属性的CSV。我想做的是添加一行,如果脚本运行且未找到非活动帐户,则会在CSV中写入类似“未找到用户”的内容。谷歌搜索到目前为止已经证明是徒劳的,所以任何输入都是有帮助的。谢谢 #EXPIRES INACTIVE ACCOUNTS AND MOVES THEM TO DISABLED OU #Toda

因此,我是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'

如果脚本的功能比它好。你不需要改变很多事情。是的,代码可以变得更有效,但最终结果仍然是一样的

对于您要询问的内容,您只需要从
$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
。度量对象可以返回多个值。我们只对
.Count

感兴趣,谢谢您的快速回复,这似乎正是我想要的。