Replace all in multiple CSV - Powershell - powershell

I'm attempting to replace the hostname from inside a CSV file with a blank space " ", but I am struggling to understand how this works, as when I attempt to call $env:computername it takes it as a string rather than the variable as per below:
$var = $env:computername
[io.file]::readalltext("C:\test\test.csv").replace("$var"," ") | Out-File c:\test\test-new.csv -Encoding ascii –Force
I have tested this and can see that the script is looking for the string $var in the CSV rather than the variable. Ultimately I would like to run this against a directory of CSV files that contain different hostnames in them and output the newly edited files to a separate location also.

I removed the quotes and tested this script and it worked for my test csv file
The quotes should be expanding the variable but if not you can simply pass the environmental variable directly like so:
[io.file]::readalltext("C:\test\test.csv").replace($env:ComputerName,"") | Out-File c:\test\test-new.csv -Encoding ascii –Force

Related

Exporting CSV in powershell to include the "$server" from a read-host entry

I wrote a powershell script to get a list of all installed software and version information for each of our servers. I'd like to be able to export it to a .csv file and name it after the $server name that was entered.
Export-CSV -path "C:\Scripts\Server_Audit\$server_Software_List.csv"
When I find that file in the folder, it just says .csv.
Do I need to declare that in another fashion so that it works?
An underscore is a valid part of a variable name, so it's trying to add $server_Software_List to the file path. One solution is to use $() in your string:
Export-CSV -path "C:\Scripts\Server_Audit\$($server)_Software_List.csv"

Batch Replace Multiple Texts in a file

I need to replace multiple different instances of text in a file using a .bat.
(Note: SQF is just a server config file, Encoding is not an issue)
I have tried:
powershell -Command "(gc Structures.sqf) -replace 'WOOD_WALL', 'CINDERBLOCK_WALL' | Out-File BrickMe.sqf"
powershell -Command "(gc Structures.sqf) -replace 'e614ee17-4467-4d51-a3f2-d4faa61de89e', 'a59f5b71-2b9a-45a2-85bb-ec29a47f78aa' | Out-File BrickMe.sqf"
powershell -Command "(gc Structures.sqf) -replace 'Wood Wall', 'Cinderblock Wall' | Out-File BrickMe.sqf"
But it only performs the last command. Eg. WOOD_WALL remains.
And
sed -e "s/WOOD_WALL/CINDERBLOCK_WALL/" -e "s/Wood Wall/Cinderblock Wall/" <Structures.sqf>BrickMe.sqf
Just creates an empty file called BrickMe.sqf
I have also tried a VBScript to no avail. I would rather keep it able to run on any Windows machine provided the code can handle the file size but I don't know how to replace multiple instances of different text without repeating the whole command and taking a long time.
I have also looked at this http://www.dostips.com/?t=batch.findandreplace
But was unsure of where to put my "WOOD_WALL" instances and my file names.
I have found heaps of results on google for replacing 1 piece of text in multiple files but hardly anything on replacing multiple texts in 1 file.
The Story:
I am running an Arma 3 server and have built a wooden admin base in game that I wish to convert to a cinderblock base. I have done this before but only manually by replacing the Instance Name, Instance_ID and Entity Name. I would like to do it using a batch file if possible and upload it to http://www.exilemod.com to help other admins. The files are usually no larger then 15 Megabytes in size.
I'm pretty awesome with Windows batch files but am new to PowerShell.
It's no wonder that your actions are not successfull.
You always take the original input file, perform actions and save to the same output file this way overwriting the previous action.
For better understanding the PowerShell part broken up:
(gc Structures.sqf) -replace 'WOOD_WALL', 'CINDERBLOCK_WALL' `
-replace 'e614ee17-4467-4d51-a3f2-d4faa61de89e',
'a59f5b71-2b9a-45a2-85bb-ec29a47f78aa' `
-replace 'Wood Wall', 'Cinderblock Wall' |
Out-File BrickMe.sqf
As the -replace operator is RegEx based the 1st and 3rd replace can be joined by:
placing a character class [_ ] underscore or space inside
a capture group ([_ ]) and
using the capture group in the replacement string $1
(gc Structures.sqf) -replace 'WOOD([_ ])WALL', 'CINDERBLOCK$1WALL' `
-replace 'e614ee17-4467-4d51-a3f2-d4faa61de89e',
'a59f5b71-2b9a-45a2-85bb-ec29a47f78aa' |
Out-File BrickMe.sqf
All this wrapped again in a cmd line:
powershell -NoProfile -Command "(gc Structures.sqf) -replace 'WOOD([_ ])WALL', 'CINDERBLOCK$1WALL' -replace 'e614ee17-4467-4d51-a3f2-d4faa61de89e','a59f5b71-2b9a-45a2-85bb-ec29a47f78aa'|Out-File BrickMe.sqf"

Spaces in filepath

Working on a simple script to pull workstation names from a .csv file then open a folder location on that workstation. I keep running into trouble on how to get PowerShell to not split the filepath. So far I have tried:
Single quotes: '\\$results\c$\direc\Desktop\Start Menu\Programs\Startup'
Regular quotation: "\\$results\c$\direc\Desktop\Start Menu\Programs\Startup"
Double quotes: ""\\$results\c$\direc\Desktop\Start Menu\Programs\Startup""
Backtick in front of the space: "\\$results\c$\direc\Desktop\Start` Menu\Programs\Startup"
8.3 name: "\\$results\c$\direc\Deskto~1\StartM~1\Progra~1\Startu~1"
Here is my code:
$inputFile = "C:\Users\$env:username\Desktop\workstations.csv"
$results = #()
Import-CSV -Path $inputFile -Header Workstations | % {
Invoke-Item -Path "\\$results\c$\JHMCIS\Desktop\Start Menu\Programs\Startup"
}
Everything works perfect until it reads the file path. It then kicks back an error that says the path does not exist.
Your string formatting is fine, the problem is that you just created an empty array named $results and then are adding that to the string when you do your invoke. change your last line to
% {Invoke-Item -Path "\\$($_.Workstations)\c$\JHMCIS\Desktop\Start Menu\Programs\Startup"}
Note that the above assumes that the file has no headings and only a single column that you are defining the name of using the -header param on your Import-CSV

Wrapping Powershell script and files together?

I'm currently using PS2EXE to compile my powershell script into an executable, works very well indeed!
My problem is that this script relies on other files/folders. So instead of having these out with the exe I want to also have these files 'wrapped' up into the exe along with the PS script. Running the exe will run the PS script then extract these files/folders and move them out of the exe...
Is this even possible?
Thanks for your help
A Powershell script that requires external files can be self-sustained by embedding the data within. The usual way is to convert data into Base64 form and save it as strings within the Powershell script. At runtime, create new files by decoding the Base64 data.
# First, let's encode the external file as Base64. Do this once.
$Content = Get-Content -Path c:\some.file -Encoding Byte
$Base64 = [Convert]::ToBase64String($Content)
$Base64 | Out-File c:\encoded.txt
# Create a new variable into your script that contains the c:\encoded.txt contents like so,
$Base64 = "ABC..."
# Finally, decode the data and create a temp file with original contents. Delete the file on exit too.
$Content = [Convert]::FromBase64String($Base64)
Set-Content -Path $env:temp\some.file -Value $Content -Encoding Byte
The full sample code is avalable on a blog.

Powershell: Prefix string to data inside a .txt file

Hi I'm completely new to Powershell so pardon me if this question has a really simple answer.
I would like to use Powershell to look thru a textfile, get all values and prefix and post fix these values with a character.
How can this be done?
Thanks
To add a prefix and suffix to each line of a file (with default command aliases this would be a lot shorter, but full names are clearer):
get-content input-file | `
foreach-object -process { "Prefix" + $_ + "Suffix" } | `
out-file output-file
Add -encoding UTF8 to the out-file to override the default encoding (UTF-16).
To do this in place output-file will need to be a temporary file and then replace the input-file after the processing has completed or read the input file into memory.