Script : Global Replace in Files - visual-studio

Is it possible to achieve the same effect of the Global Replace option in Visual Studio using a script ?
I need to perform some global replaces in a significant amount of files, at the present moment I am using MS Visual Studio to do a Find Replace in Files (Global Replace). Is it possible to achieve this using a script to run on a Windows machine? Will there be any implications or differences in the result using the proposed script as compared to the VS option?
I have long lost touch writing scripts hence might need some refreshers on this matter.

If you have PowerShell, it's pretty straighforward with Get-ChildItem and a script I wrote called Replace-FileString.ps1. This blog post gives an example:
http://www.wintellect.com/cs/blogs/jrobbins/archive/2012/12/10/automatically-updating-sln-files-to-vs-2012.aspx
Here's another example:
Get-ChildItem -path D:\Path -filter *.txt -recurse | Replace-FileString.ps1 -pattern 'find me' -replacement 'replace me' -overwrite
The above command would get all *.txt files in D:\Path (and subdirectories), and for each of the .txt files, it would replace the string "find me" (without quotes) with "replace me" (without quotes). The Replace-FileString.ps1 script's -overwrite parameter overwrites the original file with the file containing the replaced string.
Bill

Related

Best method to automate across platforms

On a daily basis I edit G code to be run on a CO2 laser and I must remove the same string from every file before running it. Currently I open each file in notepad and do ctrl + h and replace it that way. I am looking for a more efficient way to do it.
I am given a packet with a run number (ie 123456), and that run number corresponds to a directory on the network. In that directory are a number of .txt or .nc files that require the string to be removed.
Each run directory is contained in a file structure that looks like this
"\\server\x\companyname\123456"
In \companyname\ there could be hundreds of run directories, all 6 digits - these are the run numbers and are different for each case. I would like to be able to create a program that prompts me for the the run number, and then finds that directory in \x, or rather the complete path as \companyname changes based on the run number, and then replace the string in each file within the \123456 directory. So if the string is Y11 and I was given the run number 000001, I would be prompted for the run number, it would search for the directory and set the path to \\server\x\walmart\000001\ and search each file in this directory for the string Y11 and delete it.
I tried using powershell and was able to find the run folder using Prompt and get-childitem using -recurse and setting a prompted variable to use for -include, however the system doesn't allow scripts!
I can't run scripts because it's a work computer. It says the execution of scripts are disabled on this system. Basically get-executionpolicy is set to restricted and I don't have a cert for this.
This is the code i have so far
$Run = Read-Host prompt "What is the run number?"
$Files = Get-ChildItem -Path "\\\server\x\" -Filter "$Run" -recurse
foreach ($file in $files)
(Get-object $file.PSPath) |
Foreach-Object {$_ -replace "G33", ""} |
Set-Content $file.PSPath
The last portion starting with foreach is something I copied and pasted off a previous example. I have very little experience with powershell. So the run number is located in a directory two levels below x\, for and when the user is prompted for the run number I want it to search all of x, locate the path including the directory that contains the run number (walmart in the example above), and then get all the files in the run number folder. Those files would have a path like
\server\x\walmart\000001\118000001_01.NC
There can be many files in this run folder, and they all need to have the string G33 removed from them.
I am new to this, can someone please explain step by step using powershell, visual basic or any method you think would be the easiest? Even java! I am hoping to be able to use this across PCs with different operating systems. Mostly windows. Thanks!
One possible solution is having an administrator for that server run PowerShell's Set-ExecutionPolicy RemoteSigned commandlet, so that local PowerShell scripts can be executed. Note that on Windows 64-bit, this might need to be done from both a 64-bit PowerShell prompt and from a 32-bit PowerShell prompt, to ensure local PowerShell scripts could be executed from either PowerShell.
Another approach is to use sed (short for Stream Editor), a classic Unix utility that is available on Linux, macOS and Windows. For the latter, search Google for UnixUtils on SourceForge, which includes sed and several other classic Unix utilities built for Windows. Sed can do global search-and-replace within text files. It is non-interactive and meant to be executed from a script (or Batch File).
A VBScript can also read each text file and do search-and-replace. You can open the text file and using a loop read each line. If a line contains the search string, replace that text (optionally with nothing) and then write it; otherwise write it unmodified. You write to a temp file in the same path as the file you're reading, and when done you delete the original and rename the new temp file to the original file name. You have to do error checking all along the way.
As for locating the sub-folders by Run Number, you can probably do that with a batch file (or bash script on Linux and macOS). Something like this:
#echo off
:get-directory-list
dir \\server\x /S /B /AD /OGNE > "C:\Users\Me\Desktop\ListOfDirectories.txt"
:prompt-runnumber
SET RUNNUMBER=
SET /P RUNNUMBER= Enter the 6-digit run number:
if not defined RUNNUMBER echo invalid input & goto prompt-runnumber
if /i "%RUNNUMBER%" EQU "q" goto :EOF
:get-dir-for-run-number
type "C:\Users\Me\Desktop\ListOfDirectories.txt" | find "%RUNNUMBER%" > nul
if ERRORLEVEL 1 echo Run Number not found & goto prompt-runnumber
type "C:\Users\Me\Desktop\ListOfDirectories.txt" | find "%RUNNUMBER%" > %TEMP%\%~n0.tmp"
set /P RUNFOLDER= < "%TEMP%\%~n0.tmp"
echo Run Folder full path is %RUNFOLDER%
:process-files-in-folder
for %%i in (%RUNFOLDER%\*.*) do (
echo Processing folder %RUNFOLDER%, file %%i
rem ... run sed, VBscript, etc. to edit file
)
You might have to edit the above batch file to use a mapped drive letter. For bash, you'd have to first mount the network share and refer to the mount point "directory".
bash offers corresponding commands to list directories, sort them, search for text strings (using grep rather than find), prompting for input, reading input from text files, etc. Both Windows Batch and bash support sub-routines (batch files can call themselves and pass a label as a parameter) if needed.

%~dp0 equivalent in powershell (using Expand-Archive cmdlet)

I'm pretty new to scripting (especially powershell) and new to Stack Overflow, so please, excuse my ignorance and please bear with me! I will do my best to specifically explain what I'm looking to do and hopefully someone can give a detailed response of what I could do to make it work..
Intended Process/Work Flow: A co-worker downloads "Install.zip" file that has all the necessary files. This "Install.zip" file contains "Setup.bat" file (for computer config), "Fubar.zip" file, 2 powershell scripts, and a custom powerplan (.pow) file. Once downloaded they will run the "Setup.bat" file and it will pretty much do all the work. Inside that batch file it calls 2 powershell scripts. 1)"Download.ps1" - Downloads some other files from the web. 2.) "Unzip.ps1" - Unzips "Fubar.zip" and places contents in another folder - C:\TEST\
Issue: I've recently gotten familiar with using %~dp0 in batch files. I want to make sure that the location where my co-worker initially downloads the Install.zip doesn't throw off my batch file. So for example.. some people will download .zip files to the "Downloads" folder, then extract contents to proper destination. Others will download the .zip to a specific folder, then extract it within that folder. [Ex: C:\Alex\Install.zip --Extraction-- C:\Alex\Install\((Content))] So I tried to not pre-define file locations due to the variables. I've gotten the %~dp0 to work everywhere I need it to in my batch file. The only issue I have is getting my powershell scripts to use same working directory that my batch file is in. *My batch file and my powershell scripts will always be in the same directory. (Wherever that may be)
Goal: I want my powershell script ("Unzip.ps1") to look for my "Fubar.zip" file in the same directory that its currently running in. (Again - Wherever that may be) I basically want to remove any variables that may throw off the powershell script. I want it to always use it's current working directory to locate Fubar.zip. I basically need powershell to either use its current working directory OR figure out a way to have it pull its current working directory and use that to look for "Fubar.zip".
my current "Unzip.ps1" powershell script is extremely basic.
Unzip.ps1:Expand-Archive -Force c:\ALEX\Install.zip\Fubar.zip -dest c:\TEST\
Batch File Command that calls the Unzip.ps1 script: Powershell.exe -executionpolicy remotesigned -File %~dp0UNZIP.ps1
Please keep in mind, I'm just learning scripting and I'm teaching myself. My knowledge is limited, but I've made it this far and this is the only part I'm stuck on. Please give clear responses. Any help or advice would be extremely appreciated! Using PowerShell 5.0
Thanks in advance!
The equivalent of cmd.exe's %dp0 in PowerShell v3+ is $PSScriptRoot:
Both constructs expand to the absolute path of the folder containing the batch file / PowerShell script at hand.
(The only difference is that %dp0 contains a trailing \, unlike $PSScriptRoot).
Thus, to make your Unzip.ps1 script reference Fubar.zip in the same folder that the script itself is located in, use:
Expand-Archive -Force $PSScriptRoot\Fubar.zip -dest c:\TEST\
Constructing the path as $PSScriptRoot\Fubar.zip - i.e., blindly joining the variable value and the filename with \ - is a pragmatic shortcut for what is more properly expressed as (Join-Path $PSScriptRoot Fubar.zip). It is safe to use in this case, but see the comments for a discussion about when Join-Path should be used.
The automatic $PSScriptRoot variable requires PS v3+; in v2-, use
Expand-Archive -Force ((Split-Path $MyInvocation.Mycommand.Path) + '\Fubar.zip') -dest c:\TEST\
From your description, I gather that Fubar.zip and Unzip.ps1 are in the same directory. We'll pretend this directory is C:\Users\Me\Temp; although I understand that may vary.
Powershell's working directory will be the directory you're in (if called from CMD) when you launch; otherwise, it'll be from $env:UserProfile. Since the .bat file always call Unzip.ps1 from the directory that it's in (C:\Users\Me\Temp), powershell.exe will find it with this command (you can still use %~dp0 here; it's not hurting anything):
powershell.exe -ExecutionPolicy RemoteSigned -File Unzip.ps1
Inside of Unzip.ps1, you'll use Get-Location:
Expand-Archive -Force "$(Get-Location)\Fubar.zip" -dest c:\TEST\
However, if the .bat file does a cd into another directory, this won't work. From your %~dp0UNZIP.ps1 example, I assume this isn't the case, but let's address it anyway. If this is the case, you need to process from where the location of the script is. So for this call the full/relational path to the .ps1:
powershell.exe -ExecutionPolicy RemoteSigned -File C:\Users\Me\Temp\Unzip.ps1
Then, your Unzip.ps1 will need to look like this:
Expand-Archive -Force "${PSScriptRoot}\Fubar.zip" -dest 'C:\TEST\'
Alternatively, you can also do some fancy path splitting, as #JosefZ suggested. The $PSCommandPath and $MyInvocation variables contain the full path to your script; which you should familiarize yourself with:
$location = Split-Path $PSCommandPath -Parent
$location = Split-Path $MyInvocation.MyCommand.Path -Parent
Expand-Archive -Force "${location}\Fubar.zip" -dest 'C:\TEST\'
Note: Of course, you wouldn't set $location twice. I'm just showing you two ways to set it.
I hope this helps!
Prior to Powershell 3
$currentScriptPath = Split-Path ((Get-Variable MyInvocation -Scope 0).Value).MyCommand.Path
Otherwise, $PsScriptRoot will work. If you're going to depend on it, though, I'd make sure you mark the script with #Requires -version 3
I'd advise against changing the PWD unless you must. Which is to say, reference the variable directly.

Invoke Windows copy from PowerShell

I am busy with creating a PowerShell script where a folder needs to be copied to another folder as a part of the script.
For this I would like to use the standard Windows copy interface and leverage from the prompts and selections like “There is already a file with the same name in this location.”, “Do you want to merge this folder”, “Do this for all”, etc. instead of programming this all myself.
I investigated a view directions:
Using the IFileOperation::CopyItem method as e.g. HowTo: Display progress dialog using IFileOperation but I could find any hint of how to embed this in PowerShell
Using Verbs() Copy/Paste but although the example Invoke-FileSystemVerb -Path "C:\TestDir -Verb Cut; Invoke-FileSystemVerb -Path "\\server\share" -Verb Paste” suggests otherwise, I can paste files that are manually copied/cut but could not copy/cut files with using the CmdLet or simply using the Verb.DoIt() method (I suspect this for a security reason).
Simulate a drag-drop?
But could not find any working solution.
Any suggestion how to do this from PowerShell?
I use this to extract from ZIP files which seems to come up with all the prompts and progress bar:
$shell = New-Object -Com Shell.Application
$folder = $shell.NameSpace(“$path\Folder”)
$shell.NameSpace($otherpath).CopyHere($folder)

Powershell issue when executing .ps1 script

So, warning, this is probably a really newbie questions, so apologies in advance.
I'm starting to learn Powershell and one of the first things I want to do, is just make a directory & copy a file to it.
Now, if I use the following commands in a CMD window, they work perfectly.
mkdir %HOMEPATH%\test
cp test.txt %HOMEPATH%\test
However, when I put them into a .ps1 file and execute it, I get an error saying the directory could not be found etc (see below)
Copy-Item : Could not find a part of the path 'C:\Chef\windowsdevbox-master\%HOMEPATH%\.berkshelf'
Now, I got told that this is because I need to put CMD before each command. I ran this, with the CMD in front of each one and the error disappeared and instead I was presented with the "Home text" for CMD and the script finished.
Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation. All rights reserved.
However, the folder was not created and the file was not copied over.
I just wondered what I need to do to get this to work.
In PowerShell mkdir is a built in function designed to emulate the same functionality, but using the built in cmdlet New-Item to do the underlying work.
cp is a straight up alias to PowerShell's Copy-Item cmdlet.
You don't need to precede these with cmd to make them work.
PowerShell does not accept the %VAR% syntax for environment variables though. Instead you would use the special $env variable, followed by a colon : followed by the variable name: $env:HOME.
mkdir $env:HOMEPATH\test
cp test.txt $env:HOMEPATH\test
%HOMEPATH% is not a PowerShell variable.
Environment variables are stored in the $env variable scope. You can access it with $env:homepath.
Here, I would use:
mkdir "${env:homepath}\test";
cp test.txt "${env:homepath}\test";
I might be inclined to use mkdir "${env:homedrive}${env:homepath}\test";, but I don't really know what you're trying to accomplish.
The curly braces here tell PowerShell that the entire contents are the variable name. The colon tends to confuse it, IMX, especially when you embed variables in strings.
Environment variables are special in PowerShell. They have their own provider. You can list them with Get-ChildItem env:, and manipulate them at the env: PSDrive.
Additional Note: Certain configurations might have unpredictable results because the strings might have too many backslashes or have backslashes in the wrong place. In this case, you might need to use Join-Path to combine the paths correctly.
Say:
$env:homedrive is 'U:'
$env:homepath is '\'
And the subfolder is '\test'
Then "${env:homepath}\test' is \\test, which looks like a UNC path. Instead you can use Join-Path ${env:homepath} '\test', which will then correctly create '\test'.
If you want to join three things, it's a bit complex:
Join-Path ${env:homedrive} (Join-Path ${env:homepath} '\test')
But that correctly creates 'U:\test' instead of 'U:\\test'.
You can also use the -Resolve option to convert a relative path to the absolute one.

PowerShell: Directory Retrieval and syntax error

A little background...I use Windows XP, Vista, and 7 quite frequently. As such, I constantly have to move my program settings from the %appdata% folder on each PC to the next. I figured that making a PowerShell script to do this for me and remove the folders after I finish would be something to ease my troubles. As I generally have my work on a flash drive, I was hoping to use relative paths, but it seems to be causing me a bit of trouble, but the biggest problem is that I don't seem to understand Powershell enough to know what mistake I'm making and how to fix it... So I came here.I figured that I could separate the task into two scripts; one for placing the directories and the second for copying them back to the original folder and removing any trace of them behind. I'll show you want I have so far. I figured retrieving them might be more difficult so I started there. Here's what I have so far. I'm using a txt file to make it easy to update the list of folders I want or need transferred so it's also being targeted by a variable.
$fldrtxt = Get-Content .\FolderList.txt
$dirget = -LiteralPath ="'%appdata%'\$_fldertxt"
$dirpost = "./Current"
# get-command | Add-Content .\"$today"_CommandList.txt
Set-Location c: {get-content $_dirget} | %{ copy-item $_dirpost}
I can't get PowerShell to recognize the same command that I use when I use the run utility. Since I'm sure I can use %appdata% to reference where I want the folders taken from and to, how can't I write this script to do what I want? I can use an absolute path, because I'd have to use a separate script for all three computers. And that I don't want.
How can I use PowerShell to do what I want and target the folders I need to use?
First: Accerss the Environment
Since I'm sure I can use %appdata% to reference where I want the folders take from and too
Wrong syntax for PowerShell, the %var% syntax for environment variables is specific to cmd scripts (and carried forward from MS-DOS batch files).
In PowerShell to access environment variables prefix their name with env:, so $env:AppData.
$_dirget = "$env:AppData\$_fldertxt"
Second: Passing parameters
Don't include the parameter name in the variable, a variable passed to a cmdlet will be passed as an argument not a parameter name. You need:
get-content -LiteralPath $_dirget
(There is something call "splat" that allows you to use a hash tables of parameter name-argument pairs as a hashtable, but that's unnecessary here.)

Resources