Powershell - Get partial name as Variable - powershell

First posting here, and I'm a beginner in Powershell (Or most script, in the matter of fact).
What a try to do here is to take a part of a name file, and use it later To download a file from our server with the same name.
$name = Get-childitem -Path "$env:USERPROFILE\AppData\Local\Microsoft\Outlook\*.ost" -name
$username = $name.Remove($name.IndexOf('#'))
Write-Output $Username
I only get the the file name without what I put between ${.}
Thanks for any help

Split the string on the # and grab only the first item from the resulting array:
$name = "FirstName.LastName#company.com - more text you don't care about.ost"
# String.Split() returns an array of strings, `[0]` gives us the first item in that array
$username = $name.Split('#')[0]
Alteratively, remove everything from the original string beginning at the first #:
$username = $name.Remove($name.IndexOf('#'))

Related

How to pass in a .txt file to make a list of type string in PowerShell

I have a .txt file called name.txt that is in the same location as my .ps1 script.
I want to pass in the names.txt into my TestPS1.ps1 script as an array so I can iterate over different servers.
Code here:
$args1 = 'ServerName', 'SererName2'
$ArrComputers = $args1
$OutArray = #()
Clear-Host
foreach ($Computer in $ArrComputers)
{
.....
}
Names.txt:
"ServerName","ServerName2"
As you can see I am using the ArrComputers variable to go over the list. I want to replace both strings, the list of strings, in $args1 with an inputted list from names.txt. How would I do this?
Edit: Obviously if I run with ServerName as the name of the server this will not work. Pretend that every name in Names.txt is a valid server name
I set $args1 to be
$args1 = Get-Content .\names.txt
$args1 = $args1.Split(",")

Concatenate two strings to form an existing variable

I have a folder with multiple PDFs I need to print to different printers. I've created variables for each shared printer and depending on the first 2 letters of the PDF the printing will go to the matching printer.
I'm having trouble concatenating 2 strings to form an existing variable to use it later in the printing call.
This is what I have now (all PDFs in the dir starts with 01 for now):
# SumatraPDF path
$SumatraExe = "C:\Users\Administrador.WIN-FPFTEJASDVR\AppData\Local\SumatraPDF\SumatraPDF.exe"
# PDFs to print path
$PDF = "C:\Program Files (x86)\CarrascocreditosPrueba2\CarrascocreditosPrueba2\DTE\BOL"
# Shared printers list
$01 = '\\192.168.1.70\epson'
$02 = '\\192.168.1.113\EPSON1050'
cd $PDF
While ($true) {
Get-ChildItem | Where {!$_.PsIsContainer} | Select-Object Name | %{
$Boleta = $_.Name
$CodSucursal = $Boleta.Substring(0,2)
$CodImpresora = '$' + $CodSucursal
Write-Host $CodImpresora -> This shows literal $01 on PS ISE
Write-Host $01 -> This show the shared printer path
}
Start-Sleep -Seconds 5
}
# Actual PDF printing...
#& $SumatraExe -print-to $CodImpresora $PDF
So basically I need to call an existing variable based on 2 strings. Probably this could be achieved with a Switch but that will be too extensive.
concatenating 2 strings to form an existing variable
That won't work in PowerShell, variable tokens are always treated literally.
I'd suggest you use a hashtable instead:
# Shared printers table
$Impresoras = #{
'01' = '\\192.168.1.70\epson'
'02' = '\\192.168.1.113\EPSON1050'
}
Then inside the loop:
$Boleta = $_.Name
$CodSucursal = $Boleta.Substring(0,2)
$Impresora = $Impresoras[$CodSucursal]
Although the language syntax don't support variable variable names, you can resolve variables by name using either the Get-Variable cmdlet:
# Returns a PSVariable object describing the variable $01
Get-Variable '01'
# Returns the raw value currently assigned to $01
Get-Variable '01' -ValueOnly
... or by querying the Variable: PSDrive:
# Same effect as `Get-Variable 01`
Get-Item Variable:\01
While these alternatives exist, I'd strongly suggest staying clear of using them in scripts - they're slow, makes the code more complicated to read, and I don't think I've ever encountered a situation in which using a hashtable or an array wasn't ultimately easier :)

Powershell move output of loop into Array

It seems like a simple answer but for the life of me I cant figure it out. What I am trying to do is get a bunch of email addresses out of a text file and strip out the bit of the email past the # (e.g if the email address was adam#home.com I am interested in the adam bit).
The script below outputs the values that I want however I would like to have the output written into a array rather than to the console. What would be the best way of doing this?
Code below, thanks.
# Import the text file into a variable
$import = Get-Content c:\\temp\test.txt
# Variable to hold total number of emails
$totalEmails = $import.Count
#Variable to run loop
$start = 0
#Used as a separator to look at the first part of the email address
$separator = "#"
# Will increment by two to show the first part of the array in parts which holds the text before the #
$even = 0
# Username after #
$userName
#Strip out the text before the #
do {
$parts = $import.split($separator)
$even+=2
# This line here is whats not working, I would like to have the output of each echo written into the array $userName
$userName = echo $parts[$even]
$start++
} while ($totalEmails -gt $start)
Your email parsing doesn't make a whole lot of sense. Here's a one-liner for your question:
$Arr = #(Get-Content -Path 'C:\temp\test.txt') -replace '#.+'

Powershell to read some strings from each line

I have a requirement like:
Have a text file containing the following in the following pattern
172.26.xxy.zxy:Administrator:Password
172.26.xxy.yyx:Administrator:Password
172.26.xxy.yyy:Administrator:Password
172.26.xxy.yxy:Administrator:Password
I need my powershell script to read each word and use that word whereever required. For example,
foreach(something)
{
I want the IP's(172.26.---.---) to read and store the value as a variable.
I want to store the two words after **:** in seperate variables.
}
How can this be done? I know to read an entire file or get some specific string. But I need the same to be done on each line.Any help would be really appreciated.
Something like this? You can just split on the : and then store your variables based on the index
$contents = Get-Content C:\your\file.txt
foreach($line in $contents) {
$s = $line -split ':'
$ip = $s[0]
$user = $s[1]
$pass = $s[2]
write-host $ip $user $pass
}
minor edit: "t" missing in content.
You can write a regular expression to replace to remove the parts you do not need
$ip_address= '172.26.xxy.zxy:Administrator:Password' -replace '^(.+):(.+):(.+)$','$1'
$user= '172.26.xxy.zxy:Administrator:Password' -replace '^(.+):(.+):(.+)$','$2'
$pwd= '172.26.xxy.zxy:Administrator:Password' -replace '^(.+):(.+):(.+)$','$3'
I think the more generic and pure Powershell way would be something like this:
Select-String "(.*):(.*):(.*)" c:\file.txt |
Select #{Name="IP"; Expression = {$_.Matches.Groups[1]}},
#{Name="User"; Expression = {$_.Matches.Groups[2]}},
#{Name="Password"; Expression = {$_.Matches.Groups[3]}}
The Output would be then an array of objects each having three properties IP, User and Password. So you can now use them for your purposes, or just add more commands at the end of the pipe.

create var from .exe output in powershell

I need to make a variable from the ID number of a username
qwinsta.exe /server:vm041 derpy.herp
This returns the following output
SESSIONNAME USERNAME ID STATE TYPE DEVICE
derpy.herp 3 Disc
I need to create a variable in powershell with a value of 3 as per output above.
This code will be used to look through a number of servers to see if an individual user is logged in and disconnect them with rwinsta.exe
Here's quite a crude regular expression - I don't know qwinsta.exe so I'm not sure of the permutations of data it can return - this works with your above example though.
This will assign 3 to the variable $ID.
$output = qwinsta.exe /server:vm041 derpy.herp
$output -match ".*derpy.herp.*(\d).*"
$ID = $Matches[1]
you may be able to parameterise the username like so:
$username = "derpy.herp"
$output = qwinsta.exe /server:vm041 $username
$output -match ".*$username.*(\d).*"
$ID = $Matches[1]
HTH,
Matt
You can parse the output you are obtaining, get your ID, and then use New-Variable cmdlet to instance your variable.