Posts

Showing posts with the label Powershell

Convert Seconds To Hh:mm:ss,fff Format In PowerShell

Answer : In PowerShell 4.0 $s = "7000.6789" $ts = [timespan]::fromseconds($s) ("{0:hh\:mm\:ss\,fff}" -f $ts) Output: 01:56:40,679 In PowerShell 2.0 $s = "7000.6789" $ts = [timespan]::fromseconds($s) "{0:hh:mm:ss,fff}" -f ([datetime]$ts.Ticks) Output: 01:56:40,679 And to go back the other way... $text = "01:56:40,679" $textReformat = $text -replace ",","." $seconds = ([TimeSpan]::Parse($textReformat)).TotalSeconds $seconds Output: 7000.679 You could just use the ToString method on the TimeSpan object and specify the format you want to use. Either use one of the standard timespan formats or use a custom timespan format. For example, the following custom format gives the output you want: $ts = [timespan]::fromseconds("7000.6789") $ts.ToString("hh\:mm\:ss\,fff") This will output 01:56:40,679 Update: Updating to provide functions working in PowerShell v2 The above solution works well in PowerShe...

Bulk Crop Images From CMD/PowerShell

Answer : ImageMagick is a light-weight tool that can be used for this. Here is an example that croppes all jpg images in a directory and puts the results in a new folder: cd path/to/dir/ mogrify -crop +100+10 -quality 100 -path ../cropped *.jpg Here, 100 pixels from the left border and 10 pixels from the top are removed. See here for more information on how to use crop. Have you tried XnCovert? XnConvert is free cross-platform batch image processor, allowing you to combine over 80 actions. Compatible with 500 formats. It uses the batch processing module of XnViewMP and it is freeware and you can donate them if you find it useful. https://www.xnview.com/en/xnconvert/

Convert Unix Time With PowerShell

Answer : See Convert a Unix timestamp to a .NET DateTime . You can easily reproduce this in PowerShell. $origin = New-Object -Type DateTime -ArgumentList 1970, 1, 1, 0, 0, 0, 0 $whatIWant = $origin.AddSeconds($unixTime) Function Convert-FromUnixDate ($UnixDate) { [timezone]::CurrentTimeZone.ToLocalTime(([datetime]'1/1/1970').AddSeconds($UnixDate)) } $niceTime = Convert-FromUnixDate $ctime PS C:\> $niceTime Friday, 18 May 2012 8:24:18 p.m. $date = get-date "1/1/1970" $date.AddSeconds($unixTime).ToLocalTime()

Access #text Property Of XMLAttribute In Powershell

Answer : Besides #text , you can also access XmlAttribute 's value via Value property : $attr = $xml.SelectSingleNode("//obj/indexlist/index[@name='DATE']/@value") #print old value $attr.Value #update attribute value $attr.Value = "new value" #print new value $attr.Value Note that Value in $attr.Value is property name of XmlAttribute . It doesn't affected by the fact that the attribute in your XML named value . Don't select the attribute, select the node. The attributes of the node will be represented as properties and can be modified as such: $node = $xml.SelectSingleNode("//obj/indexlist/index[@name='DATE']") $node.value = 'foo' Use a loop if you need to modify several nodes: $nodes = $xml.SelectNodes("//obj/indexlist/index[@name='DATE']") foreach ($node in $nodes) { $node.value = 'foo' }

Can LINQ Be Used In PowerShell?

Answer : The problem with your code is that PowerShell cannot decide to which specific delegate type the ScriptBlock instance ( { ... } ) should be cast. So it isn't able to choose a type-concrete delegate instantiation for the generic 2nd parameter of the Where method. And it also does't have syntax to specify a generic parameter explicitly. To resolve this problem, you need to cast the ScriptBlock instance to the right delegate type yourself: $data = 0..10 [System.Linq.Enumerable]::Where($data, [Func[object,bool]]{ param($x) $x -gt 5 }) Why does [Func[object, bool]] work, but [Func[int, bool]] does not? Because your $data is [object[]] , not [int[]] , given that PowerShell creates [object[]] arrays by default; you can, however, construct [int[]] instances explicitly: $intdata = [int[]]$data [System.Linq.Enumerable]::Where($intdata, [Func[int,bool]]{ param($x) $x -gt 5 }) To complement PetSerAl's helpful answer with a broader answer to match the qu...

Bypass Vs Unrestricted Execution Policies

Answer : Per the comments, there should be no particular difference with how these execution policies behave. However Bypass is intended to be used when you are temporarily changing the execution policy during a single run of Powershell.exe , where as Unrestricted is intended to be used if you wish to permanently change the setting for the exeuction policy for one of the system scopes (MachinePolicy, UserPolicy, Process, CurrentUser, LocalMachine). Some examples: You are on a system where you want to change the execution policy to be permanently unrestricted so that any user could run any PowerShell script without issue. You would run: Set-ExecutionPolicy Unrestricted You are on a system where the exeuction policy blocks your script but you want to run it via PowerShell and ignore the execution policy when run. You would run: powershell.exe .\yourscript.ps1 -executionpolicy bypass You run Powershell.exe on a system where the execution policy blocks the exeuction of scri...

Connect To Remote PostgreSql Database Using Powershell

Image
Answer : Consult: https://odbc.postgresql.org/ Download: https://www.postgresql.org/ftp/odbc/versions/msi/ Data sources (ODBC) on Windows: Start → Search → odbc → User DSN → Add/Configure Example : $MyServer = "<ip>" $MyPort = "5432" $MyDB = "<database>" $MyUid = "<user>" $MyPass = "<pass>" $DBConnectionString = "Driver={PostgreSQL UNICODE(x64)};Server=$MyServer;Port=$MyPort;Database=$MyDB;Uid=$MyUid;Pwd=$MyPass;" $DBConn = New-Object System.Data.Odbc.OdbcConnection; $DBConn.ConnectionString = $DBConnectionString; $DBConn.Open(); $DBCmd = $DBConn.CreateCommand(); $DBCmd.CommandText = "SELECT * FROM tb_module;"; $DBCmd.ExecuteReader(); $DBConn.Close(); Check if the DSN exists in ODBC data source. If not you have to create one going to 'Control Panel', 'Admin. Tools', 'Data Sources (ODBC)'. Then select 'Add User DSN'- Select the PostgreSQL driver, and fill in...

'Connect-MsolService' Is Not Recognized As The Name Of A Cmdlet

Image
Answer : I had to do this in that order: Install-Module MSOnline Install-Module AzureAD Import-Module AzureAD All links to the Azure Active Directory Connection page now seem to be invalid. I had an older version of Azure AD installed too, this is what worked for me. Install this. Run these in an elevated PS session: uninstall-module AzureAD # this may or may not be needed install-module AzureAD install-module AzureADPreview install-module MSOnline I was then able to log in and run what I needed. This issue can occur if the Azure Active Directory Module for Windows PowerShell isn't loaded correctly. To resolve this issue, follow these steps. 1. Install the Azure Active Directory Module for Windows PowerShell on the computer (if it isn't already installed). To install the Azure Active Directory Module for Windows PowerShell, go to the following Microsoft website: Manage Azure AD using Windows PowerShell 2.If the MSOnline module isn't present, use Windows PowerShell to i...

Copy And Paste In Windows PowerShell

Answer : To select text in PowerShell with the mouse, just select it as usual. To copy the selected text to the clipboard you have to either hit Enter, or right-click. To paste into the PowerShell window, right click. keyboard Paste: alt + [space] , e , p Note: In current versions of Windows 10, Ctrl + C , and Ctrl + V work as expected. (Elaborating on the answer of Ƭᴇcʜιᴇ007 and Val) Mouse Select/Mark: Press left mouse button, drag, release. Copy: Right-click. Paste: With content in the clipboard, right-click. Keyboard Activate Mark: Alt + Space > e > k . Select a Block: Navigate (arrow keys, Page-down , Page-up , End , Pos1 ) to the upper left corner of the block, press and hold Shift , navigate to the lower right corner, release Shift . Copy: With a block selected, either hit Enter or Alt + Space > e > y . Paste: With content in the clipboard, Alt + Space > e > p . Depends on which PowerShell you are using. With the newer PowerGUI Script Edi...

Converting Custom Object Arrays To String Arrays In Powershell

Answer : This will give you what you want: $strArray = $ms | Foreach {"$($_.Option)$($_.Title)"} Select-Object is kind of like an SQL SELECT. It projects the selected properties onto a new object (pscustomobject in v1/v2 and Selected.<orignalTypeName> in V3). Your second approach doesn't work, because $_.Option in a string will only "interpolate" the variable $_ . It won't evaluate the expression $_.Option . You can get double-quoted strings to evaluate expressions by using subexpressions, for example, " ( . . . ) " o r " (...)" or " ( ... ) " or " ($_.Option)".