String Length different when using ISE or Powershell.exe - string

I have written a small user Interface with PowerShell in order to create checksums comfortable. At the moment I see a difference between using the ISE and the powershell itself.
When running the PowerShell script within the ISE I get perfect results.
This is the code I am using (Just a snippet):
$aaa = (Get-FileHash -Algorithm SHA512 -Path $str_filepath |
Select-Object -Property hash |
Format-Table -HideTableHeaders |
Out-string).TrimEnd().TrimStart()
So I create a checksum (SHA512) from a file. These are the results for one file as example:
Running the script in ISE:
0518E6DF62AB7B8D7A238039262C7A0E9F1F457D514EDE2BB8B3F4719340EF4B61053EC85ED30D07688B447DBC756F3A7455D7E0C84C7BCF62A8884E4715C8A0
Running the script in PowerShell:
0518E6DF62AB7B8D7A238039262C7A0E9F1F457D514EDE2BB8B3F4719340EF4B61053EC85ED30D07688B447DBC756F3A7455D7E0C84C7BCF62A8...
As you can see the string is shortend when using PowerShell. More confusing is that the shortening is not consistent. At home on my Windows 7 machine the string is even shorter then on my Windows 8.1 System at work. I know that there are some differences between ISE and PowerShell when running scripts regarding to styles. But shorter strings... Hmm.
So now the question. Does anyone of you have expierenced that difference between ISE and Powershell regarding to String length limitations? And if so. Does have anyone an answer for me how I can script it that there will be no different string results?

Do not use Format-* cmdlets if you need to process your data further. Those cmdlets are only for displaying data to a user. Instead expand the Hash property of the object Get-FileHash returns, either like this:
$str_checksum_sha512 = (Get-FileHash -Algorithm SHA512 -Path $str_filepath).Hash
or like this:
$str_checksum_sha512 = Get-FileHash -Algorithm SHA512 -Path $str_filepath |
Select-Object -Expand Hash

Related

Azure PowerShell :: how to print a list of properties

I found on this post how to print the the Azure Subscription ID:
(Get-AzContext).Subscription.id
But if I look in the official documentation of the command Get-AzContext I don't see anywhere that the .Subscription.id or .id would print that information.
How the guy who replied to that question knew such information?
Where can I find a list of properties for each command?
Commmands like Get-AzContext | fl * or Get-AzContext | gm or get-help Get-AzContext -full don't provide such list.
I want to be able to see all properties provided by commands like Get-AzResource or Get-AzSqlDatabase or any other.
Problably not the cleanest way, but as I use this trick very often and since I shared to some teammates I noticed they are using it now I guess it worths sharing :) .
Use the convertto-json -depth xx (where xx is big enough for your need and depending on the objet's complexity) to get the whole view of an object
Then you can redirect to a file and look for what you need quite easily.
In case you run Get-AzContext | convertto-json -depth 10 you will find back the subscription and the ID.

Trying to Export a CSV list of users using Active Directory Module for Windows Powershell

So the below is where I'm at so far:
import-module activedirectory
$domain = "ourdomain"
Get-ADUser -Filter {enabled -eq $true} -Properties whenCreated,EmailAddress,CanonicalName |
select-object Name,EmailAddress,CanonicalName,whenCreated | export-csv C:\Data\test.csv
Unfortunately, when I run the above I get dates in two different formats in the CSV, e.g.:
01/01/2017
1/01/2017 8:35:56 PM
The issue this poses is that there isn't really a clean way to sort them. Excel's formatting doesn't change either of these formats to be more like the other, both because of the inclusion of time in one and not the other, and because the time-inclusive format doesn't use trailing zeroes in the single digit numbers, but the time-exclusive format does.
We have an existing script that captures users using the LastLogonTimestamp attribute that does this correctly by changing the bottom line to the following:
select-object Name,EmailAddress,CanonicalName,#{Name="Timestamp"; Expression={[DateTime]::FromFileTime($_.whenCreated).ToString('yyyy-MM-dd_hh:mm:ss')}}
For some reason this expression runs properly when we query the LastLogonTimestamp attribute, but when we run this version querying the whenCreated attribute, we get an entirely blank column underneath the Timestamp header.
I'm not particularly knowledgeable about PowerShell itself, and my colleague who had found the original script for the LastLogonTimestamp just found it online and adapted it as minimally as possible to have it work for us, so I don't know if something in this line would work properly with one of these attributes and not the other. It seems strange to me though that two attributes using dates in the same program would store them in different formats though, so I'm not convinced that's it.
In any case, any help anyone can offer to help us get a uniform date format in the output of this script would be greatly appreciated - it needn't have the time included if it's easier to do away with it, though if they're equally easy we may as well keep it.
whencreated is already a [DateTime]. Notice the difference between the properties when you run something like this:
Get-ADUser TestUser -Properties lastlogon,whenCreated | select lastlogon,whenCreated | fl
(Get-ADUser TestUser -Properties lastlogon).lastlogon | gm
(Get-ADUser TestUser -Properties whenCreated).whenCreated | gm
This means that you don't have to convert to a DateTime before running the toString() method.
select-object #{Name="Timestamp"; Expression={$_.whenCreated.ToString('yyyy-MM-dd_hh:mm:ss')}}

Powershell concatenate an Environment variable with path

So I have this code:
$userprofile=Get-ChildItem Env:USERPROFILE
$localpath="$userprofile\some\path"
I would expect output of the below from $localpath:
c:\users\username\some\path
However what I get is:
System.Collections.DictionaryEntry\some\path
So, of course, something like cd $localpath fails. How would I accomplish what I need?
A convenient way to obtain the string value rather than the dictionary entry (which is technically what Get-ChildItem is accessing) is to just use the variable syntax: $Env:USERPROFILE rather than Get-ChildItem Env:USERPROFILE.
$localpath = "$env:USERPROFILE\some\path"
For more information:
PowerShell Environment Provider
about_Environment_Variables
Also, the Join-Path cmdlet is a good way to combine two parts of a path.
$localpath = Join-Path $env:USERPROFILE 'some\path'

How to get name of a USB device that is already mounted?

I'm actually writing a node script that detect if a specific USB is plugged, then it copy it content to Desktop. This is for Windows principally. To do this I manually check if 'E:\' path exists , 'F:\' , etc...
But I need to be sure that devices are the ones that I need. They got specific names, for example:
MTR12345 or MTR23RR5 or MTRTGX23.
And I need to know theses names. I searched for differents nodejs and powershell solutions but no ones fit my needs.
I need to get the name of the device that is mounted at E:\ . I'm totally new to PowerShell and NodeJS as well.
How can I do this ? Thanks for your help.
Sounds like you are just looking for the volume names. The WMI class Win32_logicaldisk would return that for mounted devices. Assuming it was populated of course. In it's simplest form:
Get-WmiObject Win32_logicaldisk | Where-Object{$_.VolumeName -eq "MyUSBKey"}
You have some specific examples and a regex query that you are trying to use to narrow down the results. So if you want to match a regex query:
Get-WmiObject Win32_logicaldisk |
Where-Object{Where-Object{$_.VolumeName -match "MTR[A-Za-z0-9]+"}} |
Select -Expand DeviceID
You could even simplify that if you wanted. Just match volumes that start with "MTR". Not as perfect as the other one but just as simple.
Get-WmiObject Win32_logicaldisk |
Where-Object{Where-Object{$_.VolumeName -match "^MTR"}} |
Select -Expand DeviceID

replace string if you dont' know rest of string in PowerShell

Please help. Trying to figure out how to replace a string in PowerShell, but don't know the rest of the string. I have this:
(Get-Content $file) -replace[regex]::Escape('file='*''),('file='+$_.BaseName) | Set-Content $file
I don't know what comes after file=
I tried my code, but it replaces it multiple times instead of just once.
So trying to replace file=* with filename=$_.BaseName.
Thanks for looking.
Just an FYI for anyone using the latest version of PowerShell Community Extensions (http://pscx.codeplex.com), there is a new command called Edit-File that handles this sort of thing nicely (works hard to preserve the file's original encoding):
Get-Item test.txt | Foreach {$bn=$_.BaseName; $_} |
Edit-File -Pattern '(file=).*' -Replace "`${1}$bn"
In theory I shouldn't need the Foreach stage but it seems I've found a limitation in how -PipelineVariable does not work with parameters that aren't pipeline bound. Hmm, add that to the Pscx backlog.

Resources