2016-07-07 47 views
0

我添加用戶登錄和註銷跟蹤腳本替代追加出口CSV PowerShell的

我發現,一些計算機不導出CSV,因爲他們的PowerShell 2.0,因爲不支持附加有什麼選擇?

$ErrorActionPreference = 'Continue' 
####**** Tracking user logon *****##### 

$username = $env:USERNAME 
$computername = $env:COMPUTERNAME 
$ipv4 = Test-Connection -ComputerName (hostname) -Count 1 | foreach { $_.ipv4address } 
$ipv6 = Test-Connection -ComputerName (hostname) -Count 1 | foreach { $_.ipv6address } 
$timeformat='MM-dd-yyyy hh:mm:ss tt' 
$time = (Get-Date).ToString($timeformat) 
$action = 'Logon' 
$filedate = 'MM-dd-yyyy' 
$filename = 'CompInfo' + ' ' + $(Get-Date).ToString($filedate) 

#Creates custom table and sorts the information 
$table= New-Object –TypeName PSObject -Property @{ 
      'Date/Time' = $time 
      'Username' = $username 
      'ComputerName'= $computername 
      'IPv4 Address' = $ipv4 
      'IPv6 Address' = $ipv6 
     'Notes/Action' = $action 
} | Select date/time, username, computername, 'IPv4 Address', 'IPv6 Address', notes/action 
$table | Export-Csv "d:\$env:username.csv" -NoClobber -append -NoTypeInformation 
+0

多個選項。一個是'Import-Csv'現有文件,再次添加新行和'Export-Csv'。另一個將解決另一種格式(或逗號 - 手動分開值) –

+0

我不認爲它的有效答案 – DisplayName

+0

這就是爲什麼我發佈它作爲評論;-)沒有'-Append'相當於'Export-Csv'在PowerShell 2.0 –

回答

1

試試這個

#Thanks to Dmitry Sotnikov 
#https://dmitrysotnikov.wordpress.com/2010/01/19/export-csv-append/ 
#### Append CSV Powershell 2.0 
function Export-CSV { 
[CmdletBinding(DefaultParameterSetName='Delimiter', 
    SupportsShouldProcess=$true, ConfirmImpact='Medium')] 
param(
[Parameter(Mandatory=$true, ValueFromPipeline=$true, 
      ValueFromPipelineByPropertyName=$true)] 
[System.Management.Automation.PSObject] 
${InputObject}, 

[Parameter(Mandatory=$true, Position=0)] 
[Alias('PSPath')] 
[System.String] 
${Path}, 

#region -Append (added by Dmitry Sotnikov) 
[Switch] 
${Append}, 
#endregion 

[Switch] 
${Force}, 

[Switch] 
${NoClobber}, 

[ValidateSet('Unicode','UTF7','UTF8','ASCII','UTF32', 
        'BigEndianUnicode','Default','OEM')] 
[System.String] 
${Encoding}, 

[Parameter(ParameterSetName='Delimiter', Position=1)] 
[ValidateNotNull()] 
[System.Char] 
${Delimiter}, 

[Parameter(ParameterSetName='UseCulture')] 
[Switch] 
${UseCulture}, 

[Alias('NTI')] 
[Switch] 
${NoTypeInformation}) 

begin 
{ 
# This variable will tell us whether we actually need to append 
# to existing file 
$AppendMode = $false 

try { 
    $outBuffer = $null 
    if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) 
    { 
     $PSBoundParameters['OutBuffer'] = 1 
    } 
    $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Export-Csv', 
    [System.Management.Automation.CommandTypes]::Cmdlet) 


#String variable to become the target command line 
$scriptCmdPipeline = '' 

# Add new parameter handling 
#region Dmitry: Process and remove the Append parameter if it is present 
if ($Append) { 

    $PSBoundParameters.Remove('Append') | Out-Null 

    if ($Path) { 
    if (Test-Path $Path) {   
    # Need to construct new command line 
    $AppendMode = $true 

    if ($Encoding.Length -eq 0) { 
    # ASCII is default encoding for Export-CSV 
    $Encoding = 'ASCII' 
    } 

    # For Append we use ConvertTo-CSV instead of Export 
    $scriptCmdPipeline += 'ConvertTo-Csv -NoTypeInformation ' 

    # Inherit other CSV convertion parameters 
    if ($UseCulture) { 
    $scriptCmdPipeline += ' -UseCulture ' 
    } 
    if ($Delimiter) { 
    $scriptCmdPipeline += " -Delimiter '$Delimiter' " 
    } 

    # Skip the first line (the one with the property names) 
    $scriptCmdPipeline += ' | Foreach-Object {$start=$true}' 
    $scriptCmdPipeline += '{if ($start) {$start=$false} else {$_}} ' 

    # Add file output 
    $scriptCmdPipeline += " | Out-File -FilePath '$Path'" 
    $scriptCmdPipeline += " -Encoding '$Encoding' -Append " 

    if ($Force) { 
    $scriptCmdPipeline += ' -Force' 
    } 

    if ($NoClobber) { 
    $scriptCmdPipeline += ' -NoClobber' 
    } 
    } 
    } 
} 



$scriptCmd = {& $wrappedCmd @PSBoundParameters } 

if ($AppendMode) { 
    # redefine command line 
    $scriptCmd = $ExecutionContext.InvokeCommand.NewScriptBlock(
     $scriptCmdPipeline 
    ) 
} else { 
    # execute Export-CSV as we got it because 
    # either -Append is missing or file does not exist 
    $scriptCmd = $ExecutionContext.InvokeCommand.NewScriptBlock(
     [string]$scriptCmd 
    ) 
} 

# standard pipeline initialization 
$steppablePipeline = $scriptCmd.GetSteppablePipeline(
     $myInvocation.CommandOrigin) 
$steppablePipeline.Begin($PSCmdlet) 

} catch { 
    throw 
} 

} 

process 
{ 
    try { 
     $steppablePipeline.Process($_) 
    } catch { 
     throw 
    } 
} 

end 
{ 
    try { 
     $steppablePipeline.End() 
    } catch { 
     throw 
    } 
} 

} 

#### Append CSV Powershell 2.0 
$ErrorActionPreference = 'Continue' 
####**** Tracking user logon *****##### 

$username = $env:USERNAME 
$computername = $env:COMPUTERNAME 
$ipv4 = Test-Connection -ComputerName (hostname) -Count 1 | foreach { $_.ipv4address } 
$ipv6 = Test-Connection -ComputerName (hostname) -Count 1 | foreach { $_.ipv6address } 
$timeformat='MM-dd-yyyy hh:mm:ss tt' 
$time = (Get-Date).ToString($timeformat) 
$action = 'Logon' 
$filedate = 'MM-dd-yyyy' 
$filename = 'CompInfo' + ' ' + $(Get-Date).ToString($filedate) 

#Creates custom table and sorts the information 
$table= New-Object –TypeName PSObject -Property @{ 
      'Date/Time' = $time 
      'Username' = $username 
      'ComputerName'= $computername 
      'IPv4 Address' = $ipv4 
      'IPv6 Address' = $ipv6 
     'Notes/Action' = $action 
} | Select date/time, username, computername, 'IPv4 Address', 'IPv6 Address', notes/action 
$table | Export-Csv "D:\$env:username.csv" -NoClobber -Append -Delimiter ',' -NoTypeInformation 
+0

這節省了我重寫我的腳本! :) 謝謝! – Nullldata