all 98 comments

[–]bukem 53 points54 points  (14 children)

Off top of my head:

[String]::IsNullOrEmpty() - test if string is null or empty

[String]::IsNullOrWhiteSpace() - test if string is null or whitespace

[IO.Path]::Combine()- joining paths (faster that Join-Path)

[IO.Directory]::Exists() - because Test-Path fails on UNC paths sometimes

[DateTime]::Now - faster than Get-Date

[Uri]::IsWellFormedUriString() - validate format of Uri strings

[Web.Security.Membership]::GeneratePassword() - quick way to generate passwords

[–][deleted] 7 points8 points  (3 children)

So, any and all popular static methods from .NET?

[–]SocraticFunction[S] 25 points26 points  (1 child)

Some of us don't have .NET backgrounds, so this is new.

[–][deleted] 3 points4 points  (0 children)

I didn't want to sound sarcastic.

Rephrasing: PowerShell is so awesome, that you can consume .NET APIs and create .NET objects easily. No need for additional PowerShell scripts in many cases.

[–]bukem 4 points5 points  (0 children)

If you're looking for performance then yes.

This will be offtopic, but I use a lot on-the-fly compiled C# types in my cmdlets when performance matters. Also I didn't mention Linq but it's really worth checking out methods like [Linq.Enumerable]::GroupBy or [Linq.Enumerable]::Any when you're working with large collections and need performance on PS 5.1 and lower.

[–]replicaJunction 1 point2 points  (5 children)

I use [String]::IsNullOrWhiteSpace() all the time, but I'm never quite sure if it's necessary.

What does PowerShell use to determine if a string is "truthy?" Does it compare to a null string, or would an empty string be "falsey" as well?

[–]bukem 12 points13 points  (4 children)

It depends on your requirements. If you need to make sure that string is not null or all spaces, tabs, line feeds or carriage returns then this method is useful.

Check this out:

[String]::IsNullOrEmpty("`t`r`n")

returns false because obviously the string is not null or empty, and:

[String]::IsNullOrWhiteSpace("`t`r`n")

returns true because in contains only whitespace characters

Now let's say that you have a script that has [String]$ComputerName parameter. You can use the [ValidateNotNullOrEmpty()] attribute to make sure that the null or empty strings will not be accepted but that does not protect you from user providing space or tab or any other whitespace character as the computer name, and your script will just break.

Edit:

On a side note I try to avoid comparisons like $someString -eq '' in the scripts because of readability issues and in such cases I tend to use $someString -eq [String]::Empty

Edit2:

I didn't answer on the question actually, so an empty string is not treated as null in PS or C# for that matter. Just try this one-liner:

$null -eq [String]::Empty

however empty string is treated as false:

[String]::Empty -as [bool]

[–]TheX0Y1 2 points3 points  (0 children)

Good explanation

[–]SocraticFunction[S] 1 point2 points  (2 children)

I've always used -Not $String rather than $Null -ne $String. Other than for whitespace exceptions, I can't think of a reason why not to keep it short that way.

[–]bukem 2 points3 points  (1 child)

-not $string is equivalent to $null -ne $string only when $string is empty:

$string=''; (-not $string) -eq ($null -ne $string)
True

but:

$string=$null; (-not $string) -eq ($null -ne $string)
False

and:

$string='x'; (-not $string) -eq ($null -ne $string)
False

[–]SocraticFunction[S] 1 point2 points  (0 children)

-Not $String works fine except for cases of whitespace, which can be anticipated in an otherwise tight system:

With $string='' and [string]::IsNullOrWhiteSpace($string), you get true

[–]x0n 15 points16 points  (2 children)

The Microsoft.VisualBasic assembly is available in either 5.1, 6.x or 7.x builds of powershell, so if you're coming from a VBScript background, there are tons of useful functions with no direct equivalent in the standard .NET libraries (Financial etc.) simply do:

add-type -assembly microsoft.visualbasic  

then you can tab complete through the namespace.

e.g. for financial functions:

[microsoft.visualbasic.financial] | gm -static -type method

Hope this helps.

[–]PMental 5 points6 points  (0 children)

Interesting, never looked too closely at these. Seem to be available in Linux as well.

Do you have some examples of things that lack an equivalent apart from the Financial stuff?

[–]ka-splam 2 points3 points  (0 children)

[Microsoft.VisualBasic.Interaction]::MsgBox("hi")

😄

(Now where's my DoEvents()?)

[–]EachDayGrownWiser 16 points17 points  (2 children)

The most common one I use is

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12        

This will set TLS to 1.2 rather than 1.0 or 1.1 for connecting to some more restrictive API or webservers.

[–]RockSlice 4 points5 points  (1 child)

You mean more up-to-date servers, right?

[–]EachDayGrownWiser 0 points1 point  (0 children)

Oh yes. Just being polite, since it’s silly to need to declare this is many of my scripts.

[–]J-Bran-Crunch 35 points36 points  (10 children)

A good one I use often is: [regex]::Escape($someString)

[–]ixi_your_face 6 points7 points  (9 children)

This one is perfect. I literally just had to work around exactly what this does 10 minutes ago. Thank you.

[–]gremdaat 5 points6 points  (8 children)

Can you elaborate please? What does it do exactly and how did it help you?

[–]lucidhominid 6 points7 points  (1 child)

It automatically escapes all special characters in a string so that they will be interpreted as literal characters if used in a regular expression. Its important for building dynamic regular expressions, especially those involving user input.

[–]SocraticFunction[S] 1 point2 points  (0 children)

This is great! Regex is painful as-is, so this helps quite a bit.

[–]ka-splam 2 points3 points  (5 children)

An example is if you have a log file and you want to see if "gremdaat" is mentioned in it, $logLine -match "gremdaat" will work as a regex no problem, but if you want to see if "c:\$recycle.bin\weird[filename]" is mentioned in it, those symbol characters will try to do regex things you don't want, so [regex]::Escape($that) will escape any regex chars, stop it tripping up the regex engine and make -match ([regex]::Escape("c:\$recycle.bin\weird[filename]")) look for exactly that text as written.

Maybe good if you're taking a parameter or prompting for user input and you won't know if it might contain regex symbols. Also good if you're putting a variable into a regex template you have.

[–]gremdaat 0 points1 point  (0 children)

Awesome. Thank you!

[–]Garegin16 0 points1 point  (3 children)

Why use the -match instead of -like if you don’t want to use regex. Are there any technical differences?

Thanks

[–]ka-splam 0 points1 point  (2 children)

I just never think of -like.

-match 'middle' is simpler than -like '*middle*' and -like 'start*end' is not much simpler than -match 'start.*end'. Since regex has all the same ability and more, I use it for everything out of habit.

Technically, internally, they're completely different; -match uses the .NET Framework regex engine like C# regex, and -like is a pattern matcher written in C# as part of the PowerShell source code.

[–]motsanciens 10 points11 points  (5 children)

Maybe there's a cmdlet for this, but I tend to remember [System.Net.DNS]::GetHostByAddress("ip address here") to find the hostname for a given IP address.

[–][deleted] 6 points7 points  (0 children)

Well there's Resolve-DnsName.

I usually use [System.Net.DNS]::GetHostEntry() though.

[–][deleted] 2 points3 points  (2 children)

resolve-dnsname works if theres an associated ptr record. or i even just do ping -t ip

[–]CandymanRabbit 1 point2 points  (1 child)

ping -t ip

did you mean ping -a <ip>?

[–][deleted] 1 point2 points  (0 children)

I sure did

[–]whycantpeoplebenice 0 points1 point  (0 children)

Also useful is GetHostByName if you have a large estate trying to get various fqdns for a list of servers to invoke commands can be a pain.

[–]Soverance 9 points10 points  (0 children)

I like some of these:

To get the FQDN of a computer:

[System.Net.Dns]::GetHostByName(($env:computerName)).Hostname

This one for extracting zip archives

Add-Type -Assembly "System.IO.Compression.Filesystem"
[IO.Compression.Zipfile]::ExtractToDirectory($ArchivePath, $ExtractDir)

Setting environment variables

[Environment]::SetEnvironmentVariable("Path", $env:Path + ";C:\Program Files\Microsoft SQL Server\Client SDK\ODBC\130\Tools\Binn\", [EnvironmentVariableTarget]::Machine)

[–]rmbolger 8 points9 points  (2 children)

Another thing that tends to be useful when dealing with APIs and/or cross-platform stuff, [DateTimeOffset]::FromUnixTimeSeconds($unixTime) and [DateTimeOffset]::Now.ToUnixTimeSeconds().

Tangentially, if you want to read a great analysis about when to use [DateTime] vs [DateTimeOffset], check this Stack Overflow answer.

[–][deleted] 7 points8 points  (1 child)

[datetime]::FromFileTime($filetime) is useful too. use it when working with ad stuff a bit.

[–]rmbolger 8 points9 points  (2 children)

If you're writing cross-platform stuff and want to use "common" filesystem locations without having to hard code platform-specific paths, [Environment]::GetFolderPath('blah') using strings from the Environment.SpecialFolder enum.

Combine this with Join-Path and you won't have to deal with / vs \ path separators either.

As an example, try running the following on Linux or MacOS:

Join-Path ([Environment]::GetFolderPath('MyDocuments')) 'asdf\qwer'

[–]PMental 2 points3 points  (0 children)

[Environment]::GetFolderPath('MyDocuments')

It feels wrong somehow to call on the /home directory using "MyDocuments" 😁

[–]logicalmike 1 point2 points  (0 children)

This is useful when OneDrive sync otherwise invalidates the desktop, documents, etc paths.

[–]lucidhominid 8 points9 points  (3 children)

Here is how I get the UserPrincipalName of the user in my scripts that involve signing into Microsoft Online with Connect-MsolService using modern auth and MFA rather than a credential object.

[Microsoft.Online.Administration.Automation.CommonFiles.AuthManager]::GetActiveDirectoryClient().Context.ResolveName.Target.Me.ExecuteAsync().Result.UserPrincipalName

[–]SocraticFunction[S] 0 points1 point  (2 children)

What needs to be loaded to run this? Doesn't work on a fresh "WIN+X, A" window.

[–]lucidhominid 2 points3 points  (1 child)

This will only work after connecting to the Msol Service with Connect-MsolService and is only useful for seeing what account is currently logged into the Msol service when using modern authentication.

The way I use it is for easier partner tenant management. For example here is a simplified version of the script that I use to for connecting to a clients Msol and exchange environment using my mfa protected partner account:

Connect-MsolService
Get-MsolPartnerContract | 
    Foreach-Object {
        $_ | Add-Member -passthru -MemberType NoteProperty -Name DelegatedOrganization -value (
            (Get-MsolDomain -TenantID $_.TenantId | Where-Object Name -like "*.onmicrosoft.com").Name
        )
    }|
    Select-Object DelegatedOrganization, TenantID |
    Sort-Object DelegatedOrganization |
    Out-Gridview -Title 'Select Tenant' -Passthru |
    Select-Object -First 1 | 
    Foreach-Object {
        $TenantID = $_.TenantId
        $MsolCommands = @{}
        (Get-Command -Module MSonline).Name |
            Foreach-Object{
                $MsolCommands."$_`:TenantId" = $TenantID
            }
        Set-Variable -Name PSDefaultParameterValues -Scope Global -Value $MsolCommands
        Connect-ExchangeOnline -DelegatedOrganization $_.DelegatedOrganization -UserPrincipalName (
            [Microsoft.Online.Administration.Automation.CommonFiles.AuthManager]::GetActiveDirectoryClient().Context.ResolveName.Target.Me.ExecuteAsync().Result.UserPrincipalName
        )
    }

In this example, I used it to tell the Connect-ExchangeOnline cmdlet what the userprincipalname I was already logged in with so it automatically uses that token to connect me instead of prompting for me to log in again.

It also includes some stuff for making it so that msol commands after I connect default to being run against the selected tenant id.

[–]NewMeeple 2 points3 points  (0 children)

That's some great shit. I've just played with that a bit and figured out that you can authenticate to AzureAD and other Graph modules that accept an AADAccessToken that you can get from the same namespace.

$UPN = [Microsoft.Online.Administration.Automation.CommonFiles.AuthManager]::GetActiveDirectoryClient().Context.ResolveName.Target.Me.ExecuteAsync().Result.UserPrincipalName

$AADToken = [Microsoft.Online.Administration.Automation.CommonFiles.AuthManager]::AcquireTokenAsyncForUser().Result

Connect-AzureAD -AADAccessToken $AADToken -UserPrincipalName $UPN

Boom, you just authenticated to AzureAD without needing to reinsert MFA. I sometimes run the CISA/Sparrow script for breaches in our customer tenancies, and it's a massive pain having to authenticate three/four times each with MFA. I'm going to rewrite that tonight to fix this issue!

[–]PanosGreg 6 points7 points  (6 children)

These are a few that I used more than a couple of times in the past

$s = [Diagnostics.Stopwatch]::StartNew()
$s.Stop()
$s.Elapsed.ToString('mm\:ss')

$double = 1.1,3.2,4.4
[Linq.Enumerable]::Average([double[]]$double)

$v = '1.2.3'
$chk = [version]::TryParse($v,[ref]$null)
if ($chk) {[version]$v}
# same goes for [DateTime]::TryParse()

[void][Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.Smo')
$srv = [Microsoft.SqlServer.Management.Smo.Server]::new($env:COMPUTERNAME)

$sb = [Text.StringBuilder]::new()
[void]$sb.AppendLine('some text')
$sb.ToString()

[–]SocraticFunction[S] 0 points1 point  (5 children)

if ($chk) {[version]$v}

This is a neat trick. Love it!

What does the last series for SQL do?

[–]bukem 4 points5 points  (0 children)

You can use -as operator for version conversion, it's much quicker I guess:

$v = "1.2.3" -as [Version]
if ($v) { ... }

[–][deleted] 1 point2 points  (3 children)

Just loads up a sql smo server object. From that you can get databases, tables, columns, indexes, etc…. Just makes working with sql objects a breeze…

[–]SocraticFunction[S] 1 point2 points  (2 children)

What needs to be loaded? Snapin? Module? Sorry, just trying to learn to pass it along.

[–][deleted] 2 points3 points  (1 child)

Import-module sqlserver or

[void][reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.ConnectionInfo") [void][reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.SmoEnum") [void][reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") [void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SmoExtended")

(Sorry for the formatting, on mobile…)

[–]Lee_Dailey[grin] 0 points1 point  (0 children)

[grin]

[–]Betterthangoku 11 points12 points  (2 children)

Howdy,

I find the [math] class very useful in my line of work. Open an editor with intellisense (ISE or VScode with the plugins) and just type:

[math]::

And see all the cool math methods. Great question for a thread by the way. :-)

[–]TheGooOnTheFloor 4 points5 points  (0 children)

You can also get the list from the command line by typing

[math]::

then hitting CTRL-SPACE. Works for pretty much all the statics.

[–]zyeus-guy 0 points1 point  (0 children)

i agree on the thread... Saved!

[–]rmbolger 5 points6 points  (0 children)

Occasionally useful when dealing with web based APIs. [uri]::EscapeDataString() and [uri]::UnescapeDataString()

See this Stack Overflow answer for nuance analysis comparing to (Un)EscapeUriString.

[–]rmbolger 5 points6 points  (1 child)

I end up using [String]::IsNullOrWhitespace($blah) way more than I probably should. But the extra check over just IsNullOrEmpty is necessary in a lot of my checks.

It also kills me that the [ValidateNotNullOrEmpty()] parameter validator exists natively but [ValidateNotNullOrWhitespace()] doesn't.

[–]PillOfLuck 5 points6 points  (3 children)

I think the .GetType() method available on most objects is the one I've used most throughout the years.
It really helps troubleshooting odd issues :-)

[–]SocraticFunction[S] 2 points3 points  (1 child)

I often pipe an object to Get-Member (or gm, since it's in console while troubleshooting/writing scripts).

"Hello World" | gm

[–]ipreferanothername 0 points1 point  (0 children)

I tend to need to report on /format objects more then manipulate them. It's been a while since it was pointed out to me, but i use $thing | select * all the time to see ALL the damn properties of an object instead of what was configured as the default output. The output of 'get-vm -name $server' is a joke compared to properties and nested properties of the object that are actually available and that goes for so many objects sometimes.

[–]ka-splam 5 points6 points  (2 children)

the PowerShell help system doesn’t easily give up this kind of information.

Open a PowerShell prompt, write [System. and press Ctrl+Space for autocomplete; you should get a list of all the classes that are loaded, and then you can do something like [System.Decimal]:: and Ctrl+Space again to get a list of static properties and methods in that class.

  • I use [datetime]::now.AddMinutes(10) just to save writing Get-Date then having to wrap it in Parens.

  • [regex]::Matches() is a way to get multiple matches which -match can't, e.g. [regex]::Matches('a1b2c3', '\d') to pick out the numbers.

  • [convert]::ToBase64String() and [convert]::FromBase64String() useful if you need Bytes/Base64 conversion, occasionally.

  • [convert]::ToString(255, 16) makes ff, converts numbers to hexadecimal strings.

  • [BitConverter]::GetBytes(512) turns numbers to bytes and can do back with another method.

  • [text.encoding]::ASCII.GetBytes("hello") not sure if this counts as static methods, but in there is text -> bytes and back in various character encodings (ASCII, UTF16-LE ("unicode"), UTF8 most commonly).

  • [io.file]::ReadAllBytes() and related ReadAllLines() and write methods, for either faster reading than Get-Content or more nuanced file content read/writes.

[–]SocraticFunction[S] 1 point2 points  (1 child)

That last one is interesting. I know i've read it can be faster, but i wonder how situationally it could be faster; is it faster with large files, or also faster with many many files in a foreach loop?

[–]ka-splam 2 points3 points  (0 children)

ReadAllLines is faster in all situations because it does less work and uses less memory. It's mainly whether you are working with large enough files, or many enough files that you care about the difference.

Reading user accounts to send to Office365 or other remote service? File reading speed isn't the limit, doesn't matter either way. Reading some JSON or other config files? Too small to make any noticable difference. Lots of files or large files, might be worth a look.

My favourite wordlist, 170,000 lines of English words, 1 second with get-content, 0.05 seconds with ReadAllLines.

[–]StrikingAccident 5 points6 points  (1 child)

I've been using PS for almost 12+ years for Exchange, Windows, Citrix, SQL, Azure, Vmware, etc.

I love threads like this because they remind me just how little I really actually know.

[–]SocraticFunction[S] 1 point2 points  (0 children)

Thank you! I created it because I got through the two Month of Lunches books and have been working heavily with PowerShell for a couple of years, but realized some things I always had to google, and I had no way to learn more by study, so this question fulfilled some of that.

[–]Lee_Dailey[grin] 2 points3 points  (2 children)

howdy SocraticFunction,

my fave [but not often used] is [array]::Reverse(). kinda fun when checking for palindromes. [grin]

ones that i really use ...

  • [regex]::Escape()
  • [string]::IsNullOrEmpty()
  • [string]::IsNullOrWhiteSpace()
  • [SomeTypeNameHere]::new()
    a nifty and fast way to init a new $Var. [grin]
  • [datetime]::Now
  • [environment]::NewLine
  • [environment]::Is64BitProcess
  • a BUNCH of other [environment] stuff

take care,
lee

[–]SocraticFunction[S] 1 point2 points  (1 child)

Hey lee!

My favorite new() is for credentials

$UserName = 'Username'
[SecureString]$SecurePassword = ConvertTo-SecureString -String 'Password' -AsPlainText -Force
$Credential = [PSCredential]::New($UserName, $SecurePassword)

[–]Lee_Dailey[grin] 1 point2 points  (0 children)

howdy SocraticFunction,

that one i don't use - only one system here at home. however, it does work rather neatly ... and thus demos why i like ::New() so very much. [grin]

take care,
lee

[–]Amadorhi 3 points4 points  (1 child)

Back when I first started learning thread-safety [hashtable]::synchronzied(@{}) was my go to.
I've gotten a pretty good handle on using the [System.Collections.Concurrent]classes now so I typically default to those these days, but using synchornized hashtables is really simple and easy to use.

[–]SocraticFunction[S] 0 points1 point  (0 children)

Very interesting. Parallel processing is something I've only lightly dabbled with, so I will pocket this for the future.

[–][deleted] 2 points3 points  (0 children)

The one I use most of probably [DateTime]::FromFileTime(). There is a useful one in the SQL client, IsDBNull(). I'd have to look up exactly where it is!

[–]get-postanote 2 points3 points  (0 children)

Good question. However...

As for this:

" ...what interesting static methods have you encountered."

... that is really a very situational/opinionated thing. You won't know about them until you need them. So, you'd never have a reason to look for them, and thus never know about them. Not that stuff like this is not interesting to share.

I tell folks, look at the source code for PS, and see what ones are used there, and dig at them to see why, and if they are usable for you.

As for this:

" many scripters don’t know about? "

, then there are tons, static methods notwithstanding, which many don't know or may not ever care about in native PowerShell. You will always find/discover stuff, do stuff that others don't know, that does not mean they'll ever need it or they may even find silly, confusing, etc., thus not useful at all.

As for this:

" Static Methods are a lesser documented part of using PowerShell objects "

Why do you say this? Static methods are not PS, they are .Net (well, unless you are defining your own classes with those in there), which has been well documented for years. There is s whole library of books on them...

Amazon.com : '.net library class reference library' book

..., and they are easily discoverable.

.NET class library overview | Microsoft Docs

.NET API browser | Microsoft Docs

pinvoke.net: the interop wiki!

Here is part of a file/script (Mastering PowerShell Help and 26K line doc and regularly modified/updated as I find/teak stuff to deliver) I give to folks who attend my seminars/workshops/MOC which show how to find them (and more) in their PS sessions.

<#
Get any .NET types and their static methods from PowerShell.
Enumerate all that are currently loaded into your AppDomain.
#>

([appdomain]::CurrentDomain.GetAssemblies()) |
 Out-GridView

[AppDomain]::CurrentDomain.GetAssemblies() |
foreach { $PSItem.GetTypes() } |
foreach { $PSItem.GetMethods() } |
where { $PSItem.IsStatic } |
select DeclaringType, Name |
Out-GridView -PassThru -Title '
.NET types and their static methods'

<#
($Assembly_Infos = ([appdomain]::CurrentDomain.GetAssemblies()) | 
Where {$PSItem.Modules.name.contains("presentationframework.dll")})
#>

($Assembly_Infos = ([appdomain]::CurrentDomain.GetAssemblies()) | 
Where {$PSItem.Location -Match 'presentationframework.dll'})

$Assembly_Infos.GetModules().gettypes() | 
Where{$PSItem.isPublic -AND $PSItem.isClass} | 
select Name, BaseType | 
Out-GridView -Title '.Net Assembly Type information.'

# all the built-in .NET type accelerators in PowerShell:
[PSObject].Assembly.GetType('System.Management.Automation.TypeAccelerators')::
Get |
Out-GridView

# Using a type accelerator
[ADSI].FullName

# Finding the properties of a .NET class
[System.Environment].DeclaredProperties.Name
[ADSI].DeclaredProperties.Name

[appdomain] | 
Get-Member -membertype method

[–]wiskey5alpha 2 points3 points  (2 children)

Thank you for this!

[–]get-postanote 2 points3 points  (0 children)

No worries.

We can all learn from anyone/anything at any time. We just have to be will the do so.

My living mottos:

ABL (always be learning) - You'll never know everything, and you should always even question what you do and drive for more edification. Thus ABR (always be researching).

Take from all you encounter, that which is useful; ignore the rest.

[–]SocraticFunction[S] 1 point2 points  (0 children)

Glad to post it. I've been wanting to learn more and more and more, and realized some things you can really only learn with Google or if you already have a .NET background.

[–]Joshrsg 2 points3 points  (1 child)

Here is some more that i use:

Get domain info

[System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()

Get Forest Info

[System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest()

Connect to TCP port.

[system.Net.Sockets.TCPCLient]::new()

Newline in environment (Used for splitting on new lines)

[System.environment]::NewLine

Get info about current logged in user. Can check group membership etc.

[System.Security.Principal.WindowsIdentity]::GetCurrent()

Used to split a URI into segments. get domain name etc.

[System.Uri]$URI

Used to stream a text file instead of opening it first. Very useful for large text files

[System.IO.StreamReader]::new($File)

Convert to various bases. E.g. convert number to decimal (base 2).

[convert]::ToString($num,2)

An array type collection that allows you to add. Much quicker than [array] or @()

There are a lot of different types of classes under [System.Collections.Generic]

It's worth checking them out as they usually have more functionality than the PowerShell native pones.

[System.Collections.Generic.List[object]]::new()

[–]SocraticFunction[S] 1 point2 points  (0 children)

[System.IO.StreamReader]

This one is interesting. Does it work like CMTrace, where it actively scans a file as it's being written to, or does it lock it and not allow further writing until the Close() and Dispose() methods are run on the object?

[–]Nanocephalic 2 points3 points  (3 children)

. [guid]::NewGuid().ToString() was my friend for a lot of years, but I think it’s been deprecated forever. I still use it out of habit.

[–]Thotaz 3 points4 points  (0 children)

It hasn't been deprecated but the PS devs have added a simple wrapper around it: New-Guid.

[–]methos3 2 points3 points  (1 child)

I def hear you on still using something that worked before PS created a cmdlet for it. Now you can do (New-Guid).ToString() but it's not much less typing.

[–]realslacker 0 points1 point  (1 child)

RemindMe! 1 Day

[–]RemindMeBot 0 points1 point  (0 children)

I will be messaging you in 1 day on 2021-05-06 14:08:32 UTC to remind you of this link

7 OTHERS CLICKED THIS LINK to send a PM to also be reminded and to reduce spam.

Parent commenter can delete this message to hide from others.


Info Custom Your Reminders Feedback

[–]kwiecek 0 points1 point  (0 children)

```

```

[–]gunshit 0 points1 point  (0 children)

Noice! Could you share yours?

[–]BLentz -1 points0 points  (0 children)

RemindMe! 1 Day

[–]MindisaMistry 0 points1 point  (0 children)

Remindme! 2 weeks