with a powershell script I'm exporting a list of all the DHCP Servers that exists and the scopes on the Server. The results has to be parsed in a second script in python. (Thats a system for our monitoring).
Here's the script:
$DHCPServers = (Get-DhcpServerInDC).Dnsname
$Scopes = @()
$Leases = @()
foreach ($DHCPServer in $DHCPServers) {
$Scopes = Get-DhcpServerv4Scope -ComputerName $DHCPServer | select-Object @{Name="DHCPServer"; Expression = {$DHCPServer}},ScopeID,Name,StartRange,EndRange
}
$Scopes | Export-Csv -path .\DHCP_Freeleases-Scopes-get.csv -Encoding utf8 -NoTypeInformation
foreach ($Scope in $Scopes) {
$Leases = Get-DHCPServerv4Lease -ScopeId $Scope.ScopeID -ComputerName $Scope.DHCPServer | select-Object @{Name="DHCPServer"; Expression = {$Scope.DHCPServer}}, IPAddress, @{Name="LeaseExpiryTime"; Expression = {$_.LeaseExpiryTime.toString("yyyy/MM/dd/HH:mm")}}, @{Name="ScopeID"; Expression = {$Scope.ScopeID}}, Addressstate
}
$Leases | Export-Csv -path .\DHCP_Freeleases-Leases-get.csv -Encoding utf8 -NoTypeInformation
While I wrote that script on my local DHCP Server (Windows Server 2012 R2) the CSV export was the way that I wanted it:
"dhcp1.server.intern","10.26.9.202","2022/01/25/08:22","172.26.9.192","Active"
Now I deployed the script to a different server (Windows Server 2019) and the exact same script gives me this CSVline:
"dhcp1.server.intern","10.26.9.202","2022.01.25.08:22","172.26.9.192","Active"
And I want to understand it: How can that be? I thought .toString() gives it out with my parameters?
Thanks for you help!
CodePudding user response:
The DateTime.ToString()
method treats the forward slash and the colon as format specifiers. This means that they can be replaced by locale-specific characters.
From the documentation:
The "d", "f", "F", "g", "h", "H", "K", "m", "M", "s", "t", "y", "z", ":", or "/" characters in a format string are interpreted as custom format specifiers rather than as literal characters. To prevent a character from being interpreted as a format specifier, you can precede it with a backslash (), which is the escape character.
To enforce a fixed format just escape these characters by backslashes:
$_.LeaseExpiryTime.toString("yyyy\/MM\/dd\/HH\:mm")
As you noted in the comments, you may also use a predefined format, such as 's' (ISO 8601), that is locale-independent by definition:
$_.LeaseExpiryTime.toString('s')
The output looks like 2022-01-25T11:20:26
.