Powershell脚本。从select语句修改日期

时间:2014-03-21 21:11:42

标签: powershell powershell-v2.0

这是我们正在使用的当前脚本

import-module activedirectory

Get-Aduser -SearchBase "DC=XXXX,DC=LOCAL" -Properties * -Filter {employeeType -like "User"}  | 
    Select-Object givenname, sn, SAMAccountName, mail, idautoPersonEndDate, 
        idautoPersonBirthdate, employeeNumber, employeeType, 
        @{n='OU';e={($_.canonicalname -Split "/")[-4]}} | 
    export-csv "T:\IT\Techs\Userlists\destinystudents.csv" -NoTypeInformation

我们正在尝试获得的是idautoPersonEndDate输出这样的东西。

If idautoPersonEndDate <= today-60 then write "8-31-2013" else "do nothing"

我们导入.csv文件的软件需要该字段的静态日期,并且帐户在被删除之前会保持活动一段时间。

我开始使用它的唯一方法是

$today = Get-date
$today.ToShortDateString()

Get-Aduser -SearchBase "DC=XXXX,DC=LOCAL" -Properties * -Filter {employeeType -like "User"} |
Select-Object @{n={[idautoPersonEndDate]}
if ($n -le $today)
{
    "this"
}
ELSE
{
    "NULL"
}

我可以完全出去吃午餐了解我的想法。所以任何帮助都会很棒。

1 个答案:

答案 0 :(得分:0)

看起来您最终想要csv文件中的信息,因此下面的示例创建了一个CSV文件。我希望你能用它来得到你想要的东西。

# faking data from active directory to make the sample possible to run without AD
$fakeDataFromActiveDirectory = @(
    New-OBject PSObject -Property @{ SamAccountName = "User1"; idautoPersonEndDate = (Get-Date 2012-01-01)};
    New-OBject PSObject -Property @{ SamAccountName = "User2"; idautoPersonEndDate = (Get-Date 2014-01-15)};
    New-OBject PSObject -Property @{ SamAccountName = "User3"; idautoPersonEndDate = (Get-Date 2013-12-20)};
    New-OBject PSObject -Property @{ SamAccountName = "User4"; idautoPersonEndDate = (Get-Date 2012-06-17)};
)

# using a fake "now" date, to make the sample runnable even in a couple of months
$now = Get-Date 2014-02-01
$maxAccountAge = New-TimeSpan -Days 60
$dateToCompareWith = $now - $maxAccountAge

# The "MyDateField" name can be named whatever you want your column to be named
# Also, the hashtable sent to the select statement can be shortened by using "N" and 
# "E" instead of "Name" and "Expression" if you want.
$dataWithConvertedDates = $fakeDataFromActiveDirectory | 
    Select SamAccountName, @{ Name = "MyDateField"; Expression = { 
            if ($_.idautopersonenddate -lt $dateToCompareWith)
            { 
                "8-31-2013"
            } 
            else 
            { 
                "do nothing" 
            } 
        } }

$dataWithConvertedDates | Export-Csv "C:\myoutput.csv" -NoTypeInformation