tobiaspsp / modules.psonetools Goto Github PK
View Code? Open in Web Editor NEWHome of PSOneTools, an open-source PowerShell module with tids and bits taken from articles published at https://powershell.one
License: MIT License
Home of PSOneTools, an open-source PowerShell module with tids and bits taken from articles published at https://powershell.one
License: MIT License
In case of $property is not specified the code should be:
if (@($Property).count) {
$key = $(foreach ($p in $Property) {$_.$p}) -join ', '
} else {
$properties = $_.psobject.properties.name
$key = if ($properties) {
$(foreach ($p in $properties) {$_.$p}) -join ', '
} else {"$_"}
}
Invoke-WebRequest has always been littered with problems. PowerShell 5.1's implementation doesn't have many of the features PowerShell 7's version of the command does. PowerShell 7's implementation, on the other hand, uses the new HttpClient assembly... which has been proven to be much, much slower! PowerShell/PowerShell#12764
Also, having it send the Accept-Encoding
header with gzip,deflate
as the value is a bit of a no-brainer these days, I can't really think of any situation where you wouldn't want that. The code I came up with incorporates decompressing the stream automatically, depending on the ContentEncoding property of the returned object. It seems to work quite well.
That said, my PowerShell abilities are nowhere near the level of yours. This is a massive undertaking that feels far too big for my britches. I haven't implemented anything related to doing a PUSH request yet, either. I'd like it if you could come up with an implementation appropriate to PSOne's high standard of quality.
For the purpose of deriving the ContentType ahead of time, to help safeguard the user from downloading binary data when they don't mean to, I also need to figure out a way to get the headers of the destination before any content retrieval takes place - I thought setting the Method to HEAD would accomplish that, but it turns out, a lot of websites aren't compatible with that, so I'd essentially need to have it retrieve the content for just a split second and cut it off or pause the request so the headers can be read before continuing (though I'd have setting -Force override this behavior).
Here's the code I have so far. It's a mess, but it's at least a starting point...
function Invoke-BasicWebRequest {
[CmdletBinding()]
param(
[Parameter(Position=0,Mandatory)]
[ValidateNotNullOrEmpty()]
$Uri,
[ValidateNotNullOrEmpty()]
$OutFile,
[switch]
$Force,
[ValidateNotNullOrEmpty()]
[string]
$Method='GET',
[string]
$UserAgent=[string]@(
'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'
'AppleWebKit/537.36 (KHTML, like Gecko)'
'Chrome/96.0.4664.110 Safari/537.36'))
try {
filter request {
$Request = [Net.WebRequest]::Create($Args[0])
$Request.Headers.add('Accept-Encoding',"gzip,deflate")
$Request.UserAgent = $Args[1]
$Request.Method = $Args[2]
$Response = $request.BeginGetResponse($null, $null)
$null = $Response.AsyncWaitHandle.WaitOne()
$Result = $Request.EndGetResponse($Response)
return $Result
}
if ($Method -ne 'HEAD' -and !$Force) { try {
$head = request $Uri $UserAgent HEAD
if ($head.ContentType -notlike '*charset=*' -and !$Force) {
throw 'Binary data detected, use -Force or -OutFile'
}
} catch{}}
$Result = request $Uri $UserAgent $Method
if ($Method -ne 'HEAD') { return $Result }
switch ($Result.ContentEncoding) {
'gzip' {
$Stream = [IO.Compression.GZipStream]::new($Result.GetResponseStream(), ([IO.Compression.CompressionMode]::Decompress)); break }
'deflate' {
$Stream = [IO.Compression.DeflateStream]::new($Result.GetResponseStream(), ([IO.Compression.CompressionMode]::Decompress)); break }
default {
$Stream = $Result.GetResponseStream() }
}
if ($OutFile) {
$Reader = [IO.StreamReader]::new($Stream)
Out-File -InputObject $Reader.ReadToEnd() -PSPath $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath("$OutFile")
}
elseif ($result.ContentType -like '*charset=*' -or $Force) {
$Reader = [IO.StreamReader]::new($Stream)
$Reader.ReadToEnd()
}
elseif ($head.ContentType -notlike '*charset=*' -and !$Force) {
throw 'Binary data detected, use -Force or -OutFile'
}
else {
throw 'Unknown error'
}
}
catch {
Write-Error $_.Exception.Message
}
finally {
if ($Result) { $Result.Close() }
if ($Reader) { $Reader.Close() }
}
}
If you group multiple properties standard Group-Object uses ", " (comma + space) as delimiter in the Name
field.
Line 42 has an error in join
operator argument
$key = $(foreach($_ in $Property) { $InputObject.$_ }) -join ','
It should be
$key = $(foreach($_ in $Property) { $InputObject.$_ }) -join ', '
$data = ConvertFrom-Csv @'
Region,Item,TotalSold
South,melon,47
South,orange,84
West,hammer,81
South,nail,62
East,lime,74
West,pear,88
East,drill,26
South,saw,42
East,kiwi,46
North,banana,2
'@
$data | Group-Object Region,item
Count Name Group
----- ---- -----
1 South, melon {@{Region=South; Item=melon; TotalSold=47}}
1 South, orange {@{Region=South; Item=orange; TotalSold=84}}
1 West, hammer {@{Region=West; Item=hammer; TotalSold=81}}
1 South, nail {@{Region=South; Item=nail; TotalSold=62}}
1 East, lime {@{Region=East; Item=lime; TotalSold=74}}
1 West, pear {@{Region=West; Item=pear; TotalSold=88}}
1 East, drill {@{Region=East; Item=drill; TotalSold=26}}
1 South, saw {@{Region=South; Item=saw; TotalSold=42}}
1 East, kiwi {@{Region=East; Item=kiwi; TotalSold=46}}
1 North, banana {@{Region=North; Item=banana; TotalSold=2}}
Moreover, it works incorrectly with multiple properties
$data | Group-ObjectFast -Property Region,item
Count Name Group
----- ---- -----
1 North,banana {@{Region=South; Item=nail; TotalSold=62}}
1 North,banana {@{Region=East; Item=drill; TotalSold=26}}
1 North,banana {@{Region=West; Item=hammer; TotalSold=81}}
1 North,banana {@{Region=South; Item=saw; TotalSold=42}}
1 North,banana {@{Region=West; Item=pear; TotalSold=88}}
1 North,banana {@{Region=South; Item=melon; TotalSold=47}}
1 North,banana {@{Region=East; Item=kiwi; TotalSold=46}}
1 North,banana {@{Region=East; Item=lime; TotalSold=74}}
1 North,banana {@{Region=North; Item=banana; TotalSold=2}}
1 North,banana {@{Region=South; Item=orange; TotalSold=84}}
$vmObjs is an array of Azure VM objects
$vmObjs | Group-ObjectFast -Property osType | Select-Object -Property Count, Name, Values
Count Name Values
----- ---- ------
9482 Windows
292 Windows
36837 Windows
$vmObjs | Group-Object -Property osType | Select-Object -Property Count, Name, Values
Count Name Values
----- ---- ------
9482 Linux {Linux}
36837 Windows {Windows}
292 {}
Any thoughts on how to fix?
On the line:
'*'
Should be changed to: $Filter
:
[IO.DirectoryInfo]::new($Path).GetFiles($Filter, 'AllDirectories')
Without this change, the parameter $Filter is ignored.
Method .send() takes time to resolve hostname if you pass not ipaddress. So if you pass a dead name you will get an exception.
I would suggest this solution:
if (-not [bool]($ComputerName -as [ipaddress])) {
try {
$result = [System.Net.Dns]::BeginGetHostByName($ComputerName, $null, $null)
$result = if ($result.AsyncWaitHandle.WaitOne($timeout)) { [System.Net.Dns]::EndGetHostByName($result) }
if (-not $result) {return $false}
$ComputerName = $result.AddressList.IPAddressToString
} catch {return $false}
}
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.