D
D
David Fokin2020-12-24 12:14:43
PowerShell
David Fokin, 2020-12-24 12:14:43

How to add arguments from a text file to a PowerShell script?

Tell me, I have a text file listing the serial number of devices, and a PowerShell script in which, based on the serial number of the device, data about the device is obtained through api and written to a file, if you specify the serial number directly in the script, then everything works fine, but manually drive 10,000 devices impossible, how to implement automatic sequential addition of serial numbers from a txt file to a script?
PS serial numbers change dynamically.

UPD: for the test, I wrote a serial to a text file, wrote the $serial = @(Get-Content -Path "C:\serial.txt") variable,
launched a
foreach ($serialID in $serial) {
... I
add a request to the api $serial - " https://..."+$serial"+ ..."
....
if there is one value in the file, then everything is fine, if there are two or more, then apparently it immediately inserts all the values ​​into the api request and, accordingly, I get an error

Answer the question

In order to leave comments, you need to log in

4 answer(s)
V
Victor L, 2020-12-24
@Fzero0

Get-Content -Path "C:\serial.txt" -Raw

M
MaxKozlov, 2020-12-24
@MaxKozlov

It is correct to add not $serial - it contains a list of serials, but $serialID - a variable from the loop
or more logical then

# Пляски @() вокруг Get-Content не нужны, foreach и так всё переберёт как массив, если вы не на PSv2
$serials = Get-Content ...
foreach ($serial in $serials) {
  Invoke-WebRequest "https://...api..$serial..."
}

And if there are really 10000 of them, it is better to use foreach -parallel from the seventh PS or its early variants from PoshRSJob, Invoke-Parallel, ThreadJob ...

D
David Fokin, 2020-12-24
@davchik

Thank you all, I made it from my example, for some reason if you specify a serialID, it gives out a line that is in the file, and if, for example, you set serial2, then everything works correctly

A
alhaos, 2020-12-24
@alhaos

param (
    $fileWithSerialNumbersName = "d:\serials.txt"
)

# create example file
@"
00-00-000
00-00-001
00-00-002
"@ | Out-File $fileWithSerialNumbersName

Get-Content -Path "C:\serial.txt" | ForEach-Object{
    "https://...+$_+..."
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question