0

私はまだ PowerShell を使い始めたばかりです。現在、要件があれば、Web を検索して必要なコードに変更します。

現在、サーバーから RDP ユーザー ログインを抽出しようとしています。いくつかのコードを取得して更新し、invoke-command を介してリモートで実行できるようにしました。ただし、変数の 1 つに問題があります。たとえば、2019 年 9 月 1 日または 2019 年 9 月 1 日などの日付の値を入力すると、スクリプトが機能します。しかし、(Get-Date).AddDays(-7) を使用すると機能しません。私は昨日の午後ずっとこのスクリプトをテストしてきましたが、私の人生では、まだ動作させることはできません:(

これは私が問題を抱えているコードの一部です:

#$StartDate = (Get-Date).AddDays(-7).ToString("dd-MMM-yyyy") #--> does not work
#$StartDate = (Get-Date).AddDays(-7)   #--> does not work
#$StartDate = "1-Sep-2019"  #--> Works
$StartDate = "9/1/2019"  #--> Works

そして、これが私がテストしている完全なスクリプトです。静的な日付を使用せずにこれを機能させる方法について誰かがヒントを与えることができれば感謝します。助けてくれてありがとう!

Start-Transcript -path "D:\temp\Get-User-Logins_$(Get-Date -f yyyyMMddHHmm).log"

$Computers = Get-Content "D:\temp\Server list.txt"

Write-Output "Processing the computers"

$LogEntries = Invoke-Command -Computername $Computers -Authentication NegotiateWithImplicitCredential -ThrottleLimit 10 -ErrorAction "SilentlyContinue" -Scriptblock {
    # Get the date 7 days ago as start date
    #$StartDate = (Get-Date).AddDays(-7).ToString("dd-MMM-yyyy") #--> does not work
    #$StartDate = (Get-Date).AddDays(-7)   #--> does not work
    #$StartDate = "1-Sep-2019"  #--> Works
    $StartDate = "9/1/2019"  #--> Works

    $LogOutput = @()

    $LogFilter = @{
        LogName = 'Microsoft-Windows-TerminalServices-LocalSessionManager/Operational'
        ID = 22 
        StartTime = $StartDate
    }

    $LogOutput = Get-WinEvent -FilterHashtable $LogFilter

    $LogOutput | Foreach { 
        $entry = [xml]$_.ToXml()
        [array]$EVOutput += New-Object PSObject -Property @{
            TimeCreated = $_.TimeCreated
            User = $entry.Event.UserData.EventXML.User
            IPAddress = $entry.Event.UserData.EventXML.Address
            EventID = $entry.Event.System.EventID
            EventRecordID = $entry.Event.System.EventRecordID
            ServerName = $env:COMPUTERNAME
        }        
    } 

    $EVOutput
}

Write-Output "Writing the output to the file"

$FilteredOutput += $LogEntries | Select ServerName, TimeCreated, User, IPAddress, EventRecordID, @{Name='Action';Expression={
            if ($_.EventID -eq '22'){"Shell start"}
    }
}


    $FilePath = "D:\temp\$(Get-Date -f yyyyMMddHHmm)_RDP_Report.csv"
    $FilteredOutput | Sort -Property ServerName, TimeCreated | Export-Csv $FilePath -NoTypeInformation

Write-Output "Writing File: $FilePath"
Write-Output "Done!"

Stop-Transcript
4

1 に答える 1