powershell - 在输出文件中添加时间
问题描述
此脚本通过 PowerShell 将域用户添加到任何其他或远程域计算机/系统的“管理员”组。
这将返回 csv 中的最终状态,其中包含三列(计算机名称、可用性、状态)
我需要在包含时间和日期的输出文件中添加第四列。
#Create a file in the required path and update in the below command line
$Output = "C:\CSV\Output.csv"
#The output field of the computer will blank if the user is already exist in the group
Add-Content -Path $Output -Value "ComputerName,Availability,Status"
$status = $null
$availability = $null
#Save the CSV (Comma seperated) file with the server host name and the username to be added
Import-Csv C:\CSV\Computer.csv | ForEach-Object {
$Computer=$_.Computer
$User=$_.user
if (Test-Connection -ComputerName $Computer -Count 1 -Quiet) {
Write-Verbose "$Computer : Online"
$availability="Oniline"
try {
$GroupObj=[ADSI]"WinNT://$Computer/Administrators,group"
$GroupObj.PSBase.Invoke("Add",([ADSI]"WinNT://jdom.edu/$User").Path)
$status="Success"
#Update the status in the output file
Add-Content -Path $Output -Value ("{0},{1},{2}" -f $Computer, $availability, $status)
} catch {
Write-Verbose "Failed"
}
} else {
Write-Warning "$Computer : Offline"
$availability = "Offline"
$status = "failed"
#Update the status in the output file
Add-Content -Path $Output -Value ("{0},{1},{2}" -f $Computer, $availability, $status)
}
}
这是输出文件的外观,这是我想在第四列中添加日期和时间的地方:
计算机名称、可用性、状态 TD123696WJN339P,在线,成功 TD123419WJN339P,在线,成功 计算机名称、可用性、状态 5VERF9097LTIO01,离线,失败 ZF001024DJH706G,离线,失败 5MICF9017LTIO01,离线,失败
解决方案
简单的方法是在输出中添加另一个字段,即
Add-Content -Path $Output -Value "ComputerName,Availability,Status,Timestamp"
和
"{0},{1},{2},{3}" -f $Computer, $availability, $status, (Get-Date)
但是,除非您实际上想要在输出文件中有多个标题行(为什么?),否则您应该使用计算属性和Export-Csv
.
Import-Csv 'input.csv' |
Select-Object Computer, User, @{n='Status';e={
if (Test-Connection -ComputerName $_.Computer -Count 1 -Quiet) {
...
} else {
...
}
}}, @{n='Timestamp';e={Get-Date}} |
Export-Csv 'output.csv' -NoType
推荐阅读
- python-3.x - Python:NSEpy 模块:无法获取期货实时数据
- powershell - 如何从提示和代码清理中重置 csv 中所有用户的密码
- kinect - 是否有主题或服务可以了解 RTAB-MAP 中何时丢失视觉里程计估计?
- php - Laravel 5.2 - 使用带有数组值的附加方法
- out-of-memory - 如何在 PyTorch 中节省 GPU 内存使用量
- php - CSV 文件输出 - 在开头插入一个附加列
- node.js - 猫鼬填充功能什么都不做
- python - 了解 fftfreq 函数的输出和图像中单行的 fft 图
- google-play - 一个意料之外的问题发生了。请稍后再试。(686578003)
- google-authentication - 谷歌登录集成 UI 模拟器问题 iOS 13 Xode 11