Bentley Communities
Bentley Communities
  • Site
  • User
  • Site
  • Search
  • User
ProjectWise
  • Product Communities
ProjectWise
ProjectWise PowerShell Extensions Forum Cute powershell trick
    • Sign In

    • State Not Answered
    • Replies 1 reply
    • Subscribers 66 subscribers
    • Views 151 views
    • Users 0 members are here

    Cute powershell trick

    Kevin van Haaren
    Offline Kevin van Haaren 1 month ago

    Don't know if this is common practice and I've just never seen it before, or it has some fatal flaw i'm unaware of. I frequently want to set a boolean value to some other boolean value, but the other boolean value may actually be boolean or $null and I want to change the $null to some default boolean value. I used to handle this by doing:

    if ([string]::IsNullOrEmpty($otherBool)) {
        $myBool = $false
    } else {
        $myBool = $otherBool
    }

    which is a lot of typing. Now I found I can do this instead:

    # default to false if $otherBool is $null
    $myBool = $otherBool -or $false
    # default to true if $otherBool is $null
    $myBool = $otherBool -or $true
    

    When $otherBool is one of the objects below the $otherBool -or $false resutls are:

    • $null => $false
    • integer => 0 result is $false, any non-zero result is $true
    • string => empty string result is $false, any string with actual contents result is $true
    • float => seems to be same as integer
    • hash => always results true even for empty hash @{}
    • array => null array @() or @($null) is false, everything else results in $true 
    • Sign in to reply
    • Cancel
    • Brian Flaherty
      0 Offline Brian Flaherty Fri, Oct 20 2023 9:33 AM

      Thanks for sharing Kevin. I'll be checking this out. 

      • Cancel
      • Vote Up 0 Vote Down
      • Sign in to reply
      • Verify Answer
      • Cancel

    Communities
    • Home
    • Getting Started
    • Community Central
    • Products
    • Support
    • Secure File Upload
    • Feedback
    Support and Services
    • Home
    • Product Support
    • Downloads
    • Subscription Services Portal
    Training and Learning
    • Home
    • About Bentley Institute
    • My Learning History
    • Reference Books
    Social Media
    •    LinkedIn
    •    Facebook
    •    Twitter
    •    YouTube
    •    RSS Feed
    •    Email

    © 2023 Bentley Systems, Incorporated  |  Contact Us  |  Privacy |  Terms of Use  |  Cookies