Geekдля гиков

I have this code to download the file and save it but I don’t know the type of the file so when saving it I am having trouble deciding the type.

here is the code

$tokenUrl = "/api/v1/gettoken"
$bodyData = @{
"roles"= @("CONSUMER.ALLFUNCTIONS")
"callingApplicationId"="IZGpLpXoN"
"applicationKey"="XpwR3ayFVtRCbIZGpLpXoNYdBfDQLUVb"
}| ConvertTo-Json
$response = Invoke-RestMethod -Uri $tokenUrl -Method Post -ContentType 'application/json' -Body $bodyData
$token = $response[0].token
$getDocumentUrl = "/api/v1/documents/single/65a6296932aab9ed621a29e1?requestedBy=1361"
$header = @{"token"=$token}
Invoke-RestMethod -Uri $getDocumentUrl -Method Get -Headers $header -OutFile
"C:\code\65a6296932aab9ed621a29e1.tif" #<-- here I need the file type

Rohit's user avatar

Here’s what I’d do:

  • Download to disk using a temporary filename
    • Use -PassThru to make the cmdlet return the HTTP response in addition to writing to file
  • Inspect the Content-Type response header
  • Rename downloaded file to the appropriate extension
# build mime mapping table
$mimeMap = @{}
Get-ChildItem Registry::HKEY_CLASSES_ROOT\ |Where-Object { $_.PSChildName -like '.*'} |ForEach-Object { # discover associated content type(s) ($key = $_).GetValueNames() -match 'Content ?Type' |ForEach-Object { $contentType = $key |Get-ItemPropertyValue -Name $_ $mimeMap[$contentType] = $key.PSChildName }
}
#
# authenticate as normally here ...
#
# I'm assuming the real URL variables a absolute - we'll need it for the filename extraction trick below
$getDocumentUrl = "https://some.host.fqdn/api/v1/documents/single/65a6296932aab9ed621a29e1?requestedBy=1361"
# download to disk with basename grabbed from the URL and a temporary file extension
$tmpFileName = '{0}.tmp' -f ([uri]$getDocumentUrl).Segments |Select-Object -Last 1
$response = Invoke-WebRequest -Uri $getDocumentUrl -Method Get -Headers $header -PassThru -OutFile $tmpFileName
# attempt to resolve file extension based on mime type
$mimeType = $response.Headers['Content-Type'] -split ';' |Select-Object -First 1
if ($mimeMap.ContainsKey($mimeType)) { # Rename the file Get-Item -LiteralPath $tmpFileName |Rename-Item -NewName { $_.BaseName,$mimeMap[$mimeType] -join '' }
}
else { Write-Warning "Could not resolve appropriate file extension based on MIME type '$mimeType' for file '$($tmpFileName)'"
}

This approach obviously relies on media types already registered in your Windows installation – in case you need to resolve file types not likely to be found registered on the machine that’s going to be running the script, you can pre-seed the mapping table with your own custom mappings:

# build mime mapping table
$mimeMap = @{ 'image/rohits-custom-format' = '.rht'
}

Mathias R. Jessen's user avatar

Mathias R. JessenMathias R. Jessen

12 gold badges164 silver badges221 bronze badges

To complement Mathias’ helpful answer:

Assuming that the target web service specifies a suggested output file name in its response header via a Content-Disposition field – which is not guaranteed to be present – you can examine it for the appropriate filename extension or even use it directly as the output file name:

  • The simplest solution is to use curl.exe rather than Invoke-RestMethod, as it has an option to directly use the suggested file name:

    # Downloads to the suggested file name *if* specified in a
    # Content-Disposition - if not, downloading fails.
    # Note that the use of the -d option implies -X POST, i.e. a POST request
    curl -w 'Downloading to: %{filename_effective}' -LOJ -H application/json -d $bodyData $tokenUrl
    • The -w argument prints the effective filename saved to locally; without it, you’d have to infer what file was just downloaded from examining the current folder for the most recently added file; while -v (--verbose) also contains this information (by virtue of printing the response headers), it’s buried in a lot of additional information.

    • -J (--remote-header-name), which must be combined with -O (--remote-name) is what request use of the suggested file name.

    • -H (--header) specifies header fields, and -d (--data) a request body (which implies -X POST (--request POST)).

    • A note re PowerShell (Core) 7.4+:

      • v7.4.0 introduced support analogous to curl’s -O (--remote-name) option only, albeit slightly differently:

        • You can now pass a directory path to the -OutFile parameter of Invoke-WebRequest and Invoke-RestMethod, and – as with -O – the last URL segment is used as the file name. However, unlike with -O – which takes the last segment of the input URL – it is the ultimate target URL’s last segment that is used, which makes a difference if redirections are involved.
      • Supporting the equivalent of the -J (--remote-header-name) option – i.e. automatic use of a suggested file name from the Content-Disposition header field – as well is planned, but not implemented yet as of v7.4.1.

Otherwise, the fact that you’re using a POST-method request complicates matters:

  • # Sample HEAD call with a URL whose response has a 'Content-Disposition'
    # header field with a 'filename' attribute.
    $url = 'https://api.adoptium.net/v3/binary/latest/19/ga/linux/x64/jdk/hotspot/normal/eclipse'
    # -> 'OpenJDK19U-jdk_x64_linux_hotspot_19.0.2_7.tar.gz'
    (Invoke-WebRequest $url -Method Head).Headers['Content-Disposition'] -replace '^.*\bfilename\*?="?([^;"]+)?.*', '$1'
  • For POST requests, as in your case, Mathias’ answer is probably your best bet.

mklement0's user avatar

68 gold badges673 silver badges862 bronze badges

This lesson introduces PowerShell variables, constants, and data types.

:/>  TaskExplorer — расширенный Диспетчер задач для Windows

After completing this lesson, you will be able to:

  • Explain basic concepts regarding variables.
  • Describe the difference between variables and constants.
  • Understand data types and type conversions.
  • Use variables to capture user input and use that input later in script output.
# This script demonstrates the difference between numeric and string data types. # Displays 2 # Displays Int32 # Displays 11 # Displays String

Variables may be cast from one type to another by explicit conversion.

# This script demonstrates data types and data type conversion. # Displays 1.9 # Displays 2 # Displays 1.9 # Displays 1.9 # Displays True 
# This script demonstrates the difference between single quotes and double quotes. '$(1 + 2)' # Displays $(1 + 2) # Displays 3
 'Is it morning, afternoon, or evening? ' 
  1. Review Microsoft TechNet: Get-Variable and Microsoft TechNet: about_Automatic_Variables. Start a new PowerShell session and use Get-Variable to display a list of all automatic variables and values that are defined by default when a new session is started.
  2. Review Microsoft TechNet: Using the Read-Host Cmdlet. Write a script that asks the user to enter their name, and then display a greeting back to the user that includes their name, such as ‘Hello Wikiversity!’. Add a comment at the top of the script that describes the purpose of the script.
  3. Review Microsoft TechNet: about_Quoting_Rules. Experiment with the Hello script above using both using single quotes and double quotes to display the strings to ensure that you understand the difference between the two.
  4. Review Windows IT Pro: Working with PowerShell’s Data Types. Experiment with entering different types of data (integers, floating point values, dates, strings) and use GetType() to display the data type entered.
  5. Review PowerShell.cz: Explicit Type Casting Versus Strongly Typed Variables. Experiment with data type conversion (type casting) and strongly typed variables when entering different types of data.
  • A variable or scalar is a storage location and an associated symbolic name (an identifier) which contains some known or unknown quantity or information, a value.[5]
  • A constant is an identifier whose associated value cannot typically be altered by the program during its execution.[6]
  • Many programming languages employ a reserved value (often named null or nil) to indicate an invalid or uninitialized variable.[7]
  • In almost all languages, variable names cannot start with a digit (0–9) and cannot contain whitespace characters.[8]
  • A data type or simply type is a classification identifying one of various types of data, such as real, integer or Boolean, that determines the possible values for that type, the operations that can be done on values of that type; the meaning of the data; and the way values of that type can be stored.[9]
  • Type conversion, typecasting, and coercion are different ways of, implicitly or explicitly, changing an entity of one data type into another.[10]
  • The scope of a variable describes where in a program’s text the variable may be used, while the extent (or lifetime) describes when in a program’s execution a variable has a (meaningful) value.[11]
  • Scope can vary from as little as a single expression to as much as the entire program, with many possible gradations — such as code block, function, or module — in between. [12]
  • In PowerShell, a variable name always begins with a dollar sign ($).[13]
  • PowerShell variable names are not case sensitive.[14]
  • The assignment operator (=) sets a variable to a specified value. You can assign almost anything to a variable, even complete command results.[15]
  • PowerShell data types include integers, floating point values, strings, Booleans, and datetime values.
  • Variables may be converted from one type to another by explicit conversion, such as [int32]$value.
  • In Windows PowerShell, single quotes display literal strings as is, without interpretation. Double quotes evaluate strings before displaying them.[16]
  • The Read-Host cmdlet reads a line of input from the console.[17]
ASCII (American Standard Code for Information Interchange)
A character-encoding scheme originally based on the English alphabet that encodes 128 specified characters – the numbers 0-9, the letters a-z and A-Z, some basic punctuation symbols, some control codes that originated with Teletype machines, and a blank space – into 7-bit binary integers.[18]
bit
A binary digit, having only two possible values most commonly represented as 0 and 1.[19]
Boolean
A data type with only two possible values: true or false.[20]
byte
A unit of digital information in computing and telecommunications that most commonly consists of eight bits, representing the values 0 through 255.[21]
character
A unit of information that roughly corresponds to a symbol , such as in an alphabet in the written form of a natural language.[22]
floating-point
A method of representing an approximation of a real number in a way that can support a wide range of values based on a fixed number of significant digits which are scaled using an exponent.[23]
garbage collection
A form of automatic memory management in which the garbage collector attempts to reclaim memory occupied by objects that are no longer in use by the program.[24]
immutable
An object whose state or value cannot be modified after it is created.[25]
integer
A data type which represents some finite subset of whole numbers, such as -32,768 to 32,767.[26][27]
memory leak
Incorrect management of memory allocation by a program, resulting in a reduction of available memory for running applications.[28]
string
A data type which represents a sequence of characters, either as a literal constant or as some kind of variable.[29]
Unicode
A computing industry standard for the consistent encoding, representation and handling of text expressed in most of the world’s writing systems, in which a single character may be represented by one, two, or four bytes, depending on the character set and encoding used.[30]
:/>  Руководство по исправлению прав доступа к файлам

Enable JavaScript to hide answers.

Click on a question to see the answer.

1.
A variable or scalar is _____.

A variable or scalar is a storage location and an associated symbolic name (an identifier) which contains some known or unknown quantity or information, a value.

2.
A constant is _____.

A constant is an identifier whose associated value cannot typically be altered by the program during its execution.

3.
Many programming languages employ a reserved value (often named _____) to indicate an invalid or uninitialized variable.

Many programming languages employ a reserved value (often named null or nil) to indicate an invalid or uninitialized variable.

4.
In almost all languages, variable names cannot start with _____ and cannot contain _____.

In almost all languages, variable names cannot start with a digit (0–9) and cannot contain whitespace characters.

5.
A data type or simply type is _____ that determines _____, _____, _____, and _____.

A data type or simply type is a classification identifying one of various types of data, such as real, integer or Boolean, that determines the possible values for that type, the operations that can be done on values of that type; the meaning of the data; and the way values of that type can be stored.

6.
Type conversion, typecasting, and coercion are _____.

Type conversion, typecasting, and coercion are different ways of, implicitly or explicitly, changing an entity of one data type into another.

7.
The scope of a variable describes _____, while the extent (or lifetime) describes _____.

The scope of a variable describes where in a program’s text the variable may be used, while the extent (or lifetime) describes when in a program’s execution a variable has a (meaningful) value.

8.
Scope can vary from as little as _____ to as much as _____, with many possible gradations — such as _____ in between.

9.
In PowerShell, a variable name always begins with _____.

In PowerShell, a variable name always begins with a dollar sign ($).

10.
PowerShell variable names _____ case sensitive.

PowerShell variable names are not case sensitive.

11.
The assignment operator _____. You can assign almost anything to a variable, even _____.

The assignment operator (=) sets a variable to a specified value. You can assign almost anything to a variable, even complete command results.

12.
PowerShell data types include _____.

PowerShell data types include integers, floating point values, strings, Booleans, and datetime values.

13.
Variables may be converted from one type to another by _____.

14.
In Windows PowerShell, single quotes display literal strings _____. Double quotes _____.

In Windows PowerShell, single quotes display literal strings as is, without interpretation. Double quotes evaluate strings before displaying them.

15.
The Read-Host cmdlet _____.

The Read-Host cmdlet reads a line of input from the console.


You can use the Get-Service cmdlet in PowerShell to get all services on a computer, including running and stopped services.

Often you may want to use the Get-Service cmdlet to check the startup type of a particular service.

:/>  В блокноте windows появится возможность подсчитывать знаки

Method 1: Get Startup Type of All Services

This particular example will return the name and startup type of each service on our computer.

Method 2: Get Startup Type of Specific Service

This particular example will return the name and startup type for only the service named WSearch.

Method 3: Filter for Services with Specific Startup Type

This particular example will return only the services that have a startup type of Disabled.

Example 1: Get Startup Type of All Services

PowerShell Get-Service startup type

This returns the startup type of each service on our computer.

Note: The screenshot only shows the startup type for the first few services in alphabetical order.

Example 2: Get Startup Type of Specific Service

PowerShell Get-Service startup type for specific service

This returns the startup type for the service named WSearch only.

We can see that it has a startup type of Automatic.

Example 3: Filter for Services with Specific Startup Type

PowerShell Get-Service filter by startup type

Notice that this returns only the services with a startup type of Disabled.

Feel free to replace Disabled with Automatic or Manual to filter by a different startup type.

Note: You can find the complete documentation for the Get-Service cmdlet in PowerShell here.

PowerShell: How to Use Get-Service and Filter Results
PowerShell: How to Use Get-Service to Check Status of Service
PowerShell: How to Use Get-ChildItem with Filter
PowerShell: How to Use Get-ChildItem with Multiple Filters

In this article, we will show you how to use the Get-AzVM command to check the license type of an Azure VM. We will also tell you about the different license types for Azure VMs. Azure virtual machines (VMs) can be licensed in different ways, like Azure Hybrid Benefit, pay-as-you-go, and Bring Your Own License (BYOL). To know how a particular VM is licensed, you can use the PowerShell command Get-AzVM. This command will show the license type of the VM, and other information like the number of cores licensed and the license expiration date.

Steps To Check Azure Virtual Machines License Type

Step 1: Login to Azure Portal with your Microsoft account.

Step 2: Access the the Azure Cloud Shell and switch to the PowerShell console.

Note: If you are using Windows PowerShell on your local system make sure to use the installed module version of

Step 3: Switch to the target Azure subscription where your is located. Use this command to switch subscriptions.


Set-AzContext -Subscription "add subscription name or id"

Step 4: Fetch the information of your target Azure Virtual machine.


$azureVM = Get-AzVM -ResourceGroup "add rg name" -Name "add vm name"

Step 5: Now, run this command to print the license type of your Azure virtual machine.

  • Windows_Server: The VM is licensed using Azure Hybrid Benefit for Windows Server.
  • Windows_Client: The VM is licensed using Azure Hybrid Benefit for Windows Client.
  • None: The VM is not licensed using Azure Hybrid Benefit.
  • PayG: The VM is licensed using the pay-as-you-go model.

Sample Output 1:

If the virtual machine is licensed using Azure Hybrid Benefit then the output looks like this.

Sample Output 2:

This output is different from the output of a virtual machine (VM) that was deployed without using Azure Hybrid Benefit for Windows Server licensing.


Frequently Asked Questions

1. What Are The Different Azure VM Licenses?

Pay-as-you-go and Azure Hybrid Benefit are the two different Windows Server licenses for Azure VMs. These licenses are required to run Windows Server or Windows Client machines on Azure Cloud.

2. Can We Enable Azure Hybrid Benefits For Azure VM?

Yes, you can enable but you need to have an existing Windows Server licenses with Software Assurance then only you can add that Hybrid Benefits for Azure VM.

3. What Is The Ways To Enable Azure Hybrid Benefit To Azure VM?

Simple way to enable Azure Hybrid Benefit for Azure VM from Azure portal. While provisioning VM in Basic settings select the Azure Hybrid Benefit option.