Skip to content

Instantly share code, notes, and snippets.

@mark05e
Last active February 29, 2020 17:17
Show Gist options
  • Save mark05e/8b80cc666a9452d2021ac5edf2339ae7 to your computer and use it in GitHub Desktop.
Save mark05e/8b80cc666a9452d2021ac5edf2339ae7 to your computer and use it in GitHub Desktop.
My Powershell Snippets

XML to PSCustomObject

Function Convert-XMLtoPSObject {
    Param ( $XML )
    $Return = New-Object -TypeName PSCustomObject
    $xml |Get-Member -MemberType Property |Where-Object {$_.MemberType -EQ "Property"} |ForEach {
        IF ($_.Definition -Match "^\bstring\b.*$") {
            $Return | Add-Member -MemberType NoteProperty -Name $($_.Name) -Value $($XML.($_.Name))
        } ElseIf ($_.Definition -Match "^\System.Xml.XmlElement\b.*$") {
            $Return | Add-Member -MemberType NoteProperty -Name $($_.Name) -Value $(Convert-XMLtoPSObject -XML $($XML.($_.Name)))
        } Else {
            Write-Host " Unrecognized Type: $($_.Name)='$($_.Definition)'"
        }
    }
    $Return
}

Ref: https://stackoverflow.com/q/54280135/2854578

Pass Args for DOS apps

$source="C:\temp\source"
$dest="C:\temp\dest"

$what = @("/COPYALL","/B","/SEC","/MIR")
$options = @("/R:0","/W:0","/NFL","/NDL")

$cmdArgs = @("$source","$dest",$what,$options)
robocopy @cmdArgs

ref: https://serverfault.com/a/129116/527023

Measure Execution Time inside script

$StartTime = $(get-date)
# Do Stuff
$elapsedTime = $(get-date) - $StartTime
$totalTime = "{0:HH:mm:ss}" -f ([datetime]$elapsedTime.Ticks)

ref: https://stackoverflow.com/a/45031367/2854578

Convert String to datetime

($stringToDatetime1 = '5/29/2019 8:46:47 PM' | Get-Date)
Wednesday, May 29, 2019 8:46:47 PM

($stringToDatetime2 = [DateTime]::ParseExact('5/29/2019 8:46:47 PM','M/d/yyyy h:mm:ss tt',$null))
Wednesday, May 29, 2019 8:46:47 PM

($stringToDatetime3 = [Datetime]'5/29/2019 8:46:47 PM')
Wednesday, May 29, 2019 8:46:47 PM

ref: https://stackoverflow.com/a/56405001/2854578

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment