将日期输出为文件名的 powershell 脚本

-2 scripting powershell windows-server-2008 active-directory

我有一个脚本,它在下面列出了 Active Directory 中所有主机的本地管理员:

$Searcher = New-Object DirectoryServices.DirectorySearcher([ADSI]"")
$Searcher.Filter = "(objectClass=computer)"
$Computers = ($Searcher.Findall())
md C:\All_Local_Admins
Foreach ($Computer in $Computers)
{
$Path=$Computer.Path
$Name=([ADSI]"$Path").Name
write-host $Name
$members =[ADSI]"WinNT://$Name/Administrators"
$members = @($members.psbase.Invoke("Members"))
$members | foreach {$_.GetType().InvokeMember("Name", 'GetProperty',
$null, $_, $null) | out-file -append C:\All_Local_Admins\$name.txt
}
}
Run Code Online (Sandbox Code Playgroud)

此脚本将主机名称输出为 txt 文件(HOST1.txt、HOST2.txt 等)

我想要的是获取一个文本文件,其名称获取当天的日期(例如:05082014.txt --> 该文件将包含所有主机的本地管理员)

我该如何管理?

非常感谢。

sly*_*oty 7

你可以这样做:

$fileName = (Get-Date -Format ddMMyyyy) + ".txt"
$location = "C:\All_Local_Admins\"
New-Item -ItemType file -Name $fileName -Path $location 
Run Code Online (Sandbox Code Playgroud)

out-file用这个替换你的:

out-file -append -FilePath (Join-Path $location $fileName)
Run Code Online (Sandbox Code Playgroud)

  • 好的。你可以用 `(Join-Path $location $fileName)` 替换 `$location\$fileName` 以防止在其他人更新 `$location` 时丢失尾部斜杠 (3认同)