Create and Writing into a .tempo file using PowerShell Script with variables passed, a specific format - exe

I would like to create a abcd.tempo file using powershell and want to add the content in the below format :
Startdate:12/06/2020
ParamVar2:RISPA
ParamVar3:MLPL
CNTRY=USA
the above is the targeted format , i need to insert into the abcd.tempo file.
Startdate is a variable used and similar to this, other variables as well.
what i meant,Startdate, ParamVar2 , ParamVar3, CNTRY are hardcoded labels and these parameters would be filled with the dynamic values fetched from other code block in my same powershell file.
At present, am able to create a new abcd.tempo file using
new-item -filepath "$myfilepath2createFile" -itemtype File
and i added some dummy content inside that. but
am not able understand how can i create the similar structure , written above.
Another requirement is to call a EXE file from this powershell script and pass anotehr 4 parameters to the EXE
Though i used
Start-Process -FilePath $script:testingexeFile
am stuck at how to pass the 4 parameters to this EXE

Related

Mass Conversion of (macintosh) .csv to (ms-dos) .csv

I am using a program to export hundreds of rows in an Excel sheet into separate documents, but the problem is that a PLC will be reading the files and they only save in (macintosh).csv with no option for windows. Is there a way to bulk convert multiple files with different names into the correct format?
I have used this code for a single file but I do not have the knowledge to use it for multiple in a directory
$path = 'c:\filename.csv';
[System.IO.File]::WriteAllText($path.Remove($path.Length-3)+'txt',[System.IO.File]::ReadAllText($path).Replace("`n","`r`n"));
Thank you
The general PowerShell idiom for processing multiple files one by one:
Use Get-ChildItem (or Get-Item) to enumerate the files of interest, as System.IO.FileInfo instances.
Pipe the result to a ForEach-Object call, whose script-block argument ({ ... }) is invoked once for each input object received via the pipeline, reflected in the automatic $_ variable.
Specifically, since you're calling .NET API methods, be sure to pass full, file-system-native file paths to them, because .NET's working directory usually differs from PowerShell's. $_.FullName does that.
Therefore:
Get-ChildItem -LiteralPath C:\ -Filter *.csv |
ForEach-Object {
[IO.File]::WriteAllText(
[IO.Path]::ChangeExtension($_.FullName, 'txt'),
[IO.File]::ReadAllText($_.FullName).Replace("`n", "`r`n")
)
}
Note:
In PowerShell type literals such as [System.IO.File], the System. part is optional and can be omitted, as shown above.
[System.IO.Path]::ChangeExtension(), as used above, is a more robust way to obtain a copy of a path with the original file-name extension changed to a given one.
While Get-ChildItem -Path C:\*.csv or even Get-ChildItem C:\*.csv would work too (Get-ChildItem's first positional parameter is -Path), -Filter, as shown above, is usually preferable for performance reasons.
Caveat: While -Filter is typically sufficient, it does not use PowerShell's wildcard language, but delegates matching to the host platform's file-system APIs. This means that range or character-set expressions such as [0-9] and [fg] are not supported, and, on Windows, several legacy quirks affect the matching behavior - see this answer for more information.

How to open an Excel file directly from a Powershell script?

I'm using Powershell version 7.2.1
When I run the command below on Powershell, it works fine, i.e. Excel is launched and the target Excel file is opened.
& 'PATH_TO_EXCEL_EXE' 'PATH_TO_TARGET_FILE'
Howewer, when I pass this command to a scheduled task, Excel is launched but the target file isn't opened. More details about my Powershell script:
$action = New-ScheduledTaskAction -Execute "& 'PATH_TO_EXCEL_EXE' 'PATH_TO_TARGET_FILE'"
...
Register-ScheduledTask -Action $action -Trigger $trigger -TaskName "myTask"
# The line below is for testing purpose, to see if my scheduled task can launch correctly.
Start-ScheduledTask -TaskName "myTask"
Can someone tell me the reason why Powershell fails to replicate the action, when it's passed to a scheduled task as above? Any workarounds/solutions would be appreciated.
Based on ZivkoK's comment, I'm adding an answer which solves the issue:
$excelExePath = ...
$excelFile = ...
$action = New-ScheduledTaskAction -Execute $excelExePath -Argument """$excelFile"""
A scheduled task based on the action above does what it intends to do.
P.S. Triple quotes surrounding excelFile parameter are needed when the excel file path contains space characters. For example, if the excel file path is "C:\MyUser\some random file.xlsx", then Excel tries to open 3 files named "some", "random", and "file.xlsx". Using triple quotes solves this problem.

PowerShell Dynamic Creation of ADUsers from imported Excelsheet

first of all, i want to say, that i'm very, very new to PowerShell. These are the first PS-scripts i wrote.
I'm currently working on a PS-Script for AD-Administration. Currently the Scripts for Adding/Deleting SmbShares, Adding or removing Users from Groups, and so on, are already done.
I already had a working script for creating the users in AD, but it wasn't dynamic, as in hard coded variables that all would have to be entered into a new-ADUser command. As the code will be used for more than one specific set of parameters, it has to be dynamic.
I'm working with Import-Excel and found a great function here, but I'm having two problems wih this function.
$sb = {
param($propertyNames, $record)
$propertyNames | foreach-object -Begin {$h = #{} } -Process {
if ($null -ne $record.$_) {$h[$_] = $record.$_}
} -end {New-AdUser #h -verbose}
}
Use-ExcelData -Path $Path -HeaderRow 1 -scriptBlock $sb
The dynamic part of this is, that the table headers will be used as the parameternames for New-ADUser. Only thing one needs to change if the amount of parameters needed changes is add or delete a column in the excel sheet. The column header always needs the same name as the parameter of New-ADUser.
Screenshot of excel table
My Problem now is the "Type" Header i've got at column A. It is needed to specify the type of the user for adding the user to specific ADGroups. But due to the function above using all headers as parameters this doesn't work.
Has anyone an idea how to change the function $sb so that it starts with the second column? I've tried aroung with skip 1 and tried a lot of other workarounds, but with my non-experience nothing ssemed to come close to what i need.
SOLVED PROBLEM BELOW: added -DataOnly to Use-ExcelData and now it works.
The second problem would be, that the function does not stop trying to create users once there are no more values for the parameters. For trying around i deleted the column "Type". In the example of trying to create the two users testuser and testuser2, Powershell creates the users with no problems but then asks for a name for a new-ADUser.
AUSFÜHRLICH: Ausführen des Vorgangs "New" für das Ziel "CN=Test User,CN=Users,DC=****,DC=**".
AUSFÜHRLICH: Ausführen des Vorgangs "New" für das Ziel "CN=Test2 User2,CN=Users,DC=****,DC=**".
Cmdlet New-ADUser an der Befehlspipelineposition 1
Geben Sie Werte für die folgenden Parameter an:
Name:
Thank you in advance, sorry for my english and please tell me if I did something wrong forumwise.
I see you I would save the excel sheet as a CSV file and then import it. It's faster and easier to consume. The headers become your parameter names and the import behaves like any other object.
$csvData = Import-csv -path <path to csv file>
From here, iterate the rows and access the values as properties of the row. No need to import the data into a hashtable, it's already accessible with property names defined by the header row.
foreach ($row in $csvData) {
Write-Host $row.Name
Write-Host $row.Path
}
Once the loop reaches the end of the file, it stops trying to create users.
FYI, The use of single letter variables is going to make your code very difficult to maintain. My eyes hurt just looking at it.

String Expansion with Variables

I have a config file, that contains strings used within my scripts. The config file is read via a C# class using this Syntax:
$final = $PropMgr.GetValue($section, $property)
$final = $ExecutionContext.InvokeCommand.ExpandString($final)
This returns the string from the config file. Afterwards the returned string gets expanded because it may contain objects that need expansion
Everything works fine but for one thing. One of my strings in the config file looks like this:
Found $($scripts.Length) scripts to execute in the config file
$scripts is array, so the expanded string should look like this:
Found 6 scripts to execute in the config file
But using my code avove I receive an exception:
Exception calling "ExpandString" with "1" argument(s): "Object reference not set to an instance of an object."
If I debug the script and execute this code in a commandline:
$ExecutionContext.InvokeCommand.ExpandString("Found $($scripts.Length) scripts to execute in the config file")
Everything is fine, but using the $final variable instead of the string itself, I receive the exception again.
What do I have to do to achieve what I was looking for?

Powershell how to take string from file and put into a variable

I am writing a Powershell script to "build" Windows 7 PCs: adding users, printers, applications, changing settings, et al. I am adding some printer drivers using PNPUtil, but the problem is I won't know what "Published name" the drivers will be given.
If I put the output from the PNPUtil command into a .txt file, is there a way for me to then take the __.inf Published name and put it into a variable so that I can then use that name to add the printer using $printerclass.CreateInstance()?
You don't have to use a file if PNPUtil only outputs the name your interested in. That is, you can assign its output to a variable like so:
$result = pnputil.exe
BTW if you want to use a file, to read content from a file you use Get-Content:
pnputil.exe > result.txt
$result = Get-Content result.txt
$line = $result | Foreach {if ($_ -match 'assigned an (\w+\.inf)') {$matches[1]}}
Okay - I found my own solution: Once the .inf file is added, all the driver names in that .inf are stored in the Microsoft update files. I just need to know the specific name of the driver I need from each .inf file in order to add the Printers.
However, I'd still love to know how to get a string from a line from a file using Powershell.

Resources