How do i create log file (time, user who run the script and what happen after the script was done)

后端 未结 1 626
我寻月下人不归
我寻月下人不归 2021-01-26 12:17

My script makes a folder and ask for foldername then make 2 groups, then asks for what users should be in each group, and gives rights to the groups (read only and read & wr

1条回答
  •  孤城傲影
    2021-01-26 12:45

    I would suggest Start-Transcript in combination with different variables you can append to the file. This would be the easiest way.

    For example:

    Start-Transcript -Path "c:\temp\transcript.txt"
    $log = @()
    $date = Get-Date
    $user = $env:UserName
    $newFolderFull = "c:\folder"
    $log += $date, $user, $newFolderFull
    Stop-Transcript
    $log | add-content "c:\temp\transcript.txt"
    

    This works very well with Write-Output.
    For example:

        foreach ($User in $userR -split ',') {
            Add-ADGroupMember -Identity $groupnameR -members $User
            Write-Output ("{0:yyyy-MM-dd HH:mm:ss} reading rights have been granted to User {1}" -f (Get-Date),($User))
        }
    

    This will write a line in the log where {0} is replaced by the Date-Time stamp and {1} will be the User.
    The Header of the transcript will contain some infos about the host who startet the script as well, but it differs by powershell version.

    This way you will see when, who, what, where.

    0 讨论(0)
提交回复
热议问题