Posts

Showing posts from May, 2020

Preload your favorite scripts in PowerShell

Try this - if you have developed many useful scripts for yourself, how to avoid call Import-Module in all your new script? To solve this, we must find a way to preload your favorites. The trick is to create "profile.ps1" file and save it in your profile path. You will find your profile path by executing the following code: $profile.CurrentUserAllHosts After you have found out the path, create a "profile.ps1" and write all Import-Module lines to preload your favorites.

Failed to download from Internet

The following codes are downloading a text file from the Internet. It looks simple and straight forward. $u2 = "https://my-test-web.com/my-file.txt" $f2 = "my-file.txt" Invoke-WebRequest -Uri $u2 -OutFile $f2 The above code looks good and we never expect download failure except that Internet connection has broken down. But, if you look at the value of $u2, you might notice that it is calling HTTPS which require Powershell to validate the SSL certificate. So, there is a chance for the above code failed when the web server disabled Tls v1.1 and below. To resolve/avoid this issue, you must change the environment setting first before calling Invoke-WebRequest. # enforce Tls1.2 [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 $u2 = "https://my-test-web.com/my-file.txt" $f2 = "my-file.txt" Invoke-WebRequest -Uri $u2 -OutFile $f2

Tricky ConvertTo-Json in Powershell

ConvertTo-JSON is very useful for generating any runtime value into JSON format. For example, the following code convert an array into JSON format: # save the to json format $list = @(     "Apple",     "Banana" ) $list | ConvertTo-Json And the output will look like this: [     "Apple",     "Banana" ] But, there is a catch on the following situation where it does not convert the array into JSON format. Instead, it just returns a string.  $trick = @(     "Coconut" ) $trick | ConvertTo-Json And the output will look like this: "Coconut" This is not a mistake of the above code. Instead, the correct code should look like the following: ConvertTo-Json -InputObject $trick Output: [     "Coconut" ]

Handling XML in Powershell

In Powershell, it is very easy to handle XML data as compare to C#. This is because Powershell is not statically type and the property access can be determined at runtime. The following example shows how to change the value in an AppSetting node: $f = "$PSScriptRoot\web.config" # read xml file - the most import is "[xml]" type cast in front of $xml variable. [xml]$xml = Get-Content $f # show the nodes in "appSettings" $xml.configuration.appSettings.add | Format-Table -AutoSize # change the appSetting $xml.configuration.appSettings.add[1].value = "1" # save changes to file $xml.Save($f)