w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML Categories
replace tag in *dtsConfig file from powershell
Your code should be like following: ls C: empSTA*.dtsConfig | foreach { $file = $_.FullName; $xml = [xml](Get-Content $file) $todayStr = [datetime]::Today.ToString('_MMddyyy') @($xml.SelectNodes('//ConfiguredValue')) | %{ $_.'#text'=($_.'#text' -replace '_d+',$todayStr) } $xml.Save($file) }

Categories : Powershell

String replace file content with PowerShell
Use (V3 version): (Get-Content c: emp est.txt).replace('[MYID]', 'MyValue') | Set-Content c: emp est.txt Or for V2: (Get-Content c: emp est.txt) -replace '[MYID]', 'MyValue' | Set-Content c: emp est.txt

Categories : Powershell

Powershell search and replace
Your example shows you creating the text file by recursing through a folder the desktop, you don't need a text file to loop through, you could just use that, but lets say you do generate the text file of short name like you state. $short_file_names = Get-Content C:PathTo500_Short_File_Names_No_Extensions.txt Now you can loop through that array in two ways: Using the foreach keyword: foreach ($file_name in $short_file_names) { # ... } Or using the ForEach-Object cmdlet: $short_file_names | ForEach-Object { # ... } The big difference is that the current item will be a named variable $file_name in the first and a non-named built-in $_ variable in the second. Let's say you use the first. You need to see if $file_name is in the second file and if so record that you found it.

Categories : Search

Powershell - using variables in replace
Unlike the Replace method which takes strings, the replace operator takes a regular expression pattern. $SourcePath needs to be escaped as it contains backslashes which are special regex characters. $sourceFileRelativePath = $sourceFullPath -replace [regex]::escape($SourcePath) $destFullFilePath = Join-Path $folder $sourceFileRelativePath

Categories : Powershell

Powershell replace exact string
The reason why this happened is because you have used pattern WEEK. The dot was a problem: in a regular expression world, the dot means "any character". That's why it was replacing both WEEK_ and WEEK.. When you have added backslash, then the dot was escaped ie. it lost it's special meaning. Thus making it work.

Categories : Regex

Sharepoint & PowerShell - StringBuilder.Replace
Ok, sod's law that I find a solution shortly after posting on here..! The following works for me. I'd experimented with 'r and 'n with no luck, but by doing both of them together with NewLine, all line breaks are now being stripped out: $log = "C:mylogfile.csv" $newline = [System.Environment]::NewLine $charsToStrip = "`r","`n", $newline $sb2 = New-Object System.Text.StringBuilder $sb2.Append("Text fields") foreach ($char in $charsToStrip) { $sb2.Replace($char,".") } $sb2.ToString() | Out-File $log -Append

Categories : Powershell

Get pdf file from server and display it in pdf viewer in android
You can download it via FTP and save it on your SD card have a look on how get ftp file with android and this is how you can open it in a PDF reader : PackageManager packageManager = context.getPackageManager(); Intent intent = new Intent(Intent.ACTION_VIEW); intent.setType("application/pdf"); packageManager.queryIntentActivities(intent,PackageManager.MATCH_DEFAULT_ONLY); Intent pdfintent = new Intent(); pdfintent.setAction(Intent.ACTION_VIEW); Uri uri = Uri.fromFile(yourfile); pdfintent.setDataAndType(uri, "application/pdf"); context.startActivity(pdfintent);

Categories : Android

Powershell: Force immediate evaluation of backreference during replace
1st, missing the point, answer replaced... When concatenate '$1' and '6Q' (before being passed to the regex engine) you get $16Q and there is no 16th capture to replace. To avoid this, use named groups in the match ((?<name>)) and ${name} in the replacement string. See the documentation, and note: If number does not specify a valid capturing group defined in the regular expression pattern, $number is interpreted as a literal character sequence that is used to replace each match.

Categories : Powershell

Use Powershell to replace characters within a specific string
Try this regex: "(?<!?xml.*)(?<=`".*?)`"(?=.*?`")" In your code it would be: (Get-Content C: estcommunication.xml) | Foreach-Object {$_ -replace "&", "+" ` -replace "£", "GBP" ` -replace "'", "" ` -replace "–", " " ` -replace "(?<!?xml.*)(?<=`".*?)`"(?=.*?`")", ""} | Set-Content C: estcommunication.xml This will take any " that has a " in-front of and behind it (except a line that has ?xml in it) and replace it with nothing. Edit to include breakdown of regex; (?<!?xml.*)(?<=`".*?)`"(?=.*?`") 1. (?<!?xml.*)----> Excludes any line that has "?xml" before the first quote 2. (?<=`".*?)------> Lookbehind searching for a quotation mark. The ` is to escape the quotation mark, which is needed for powershell 3. `"--------------

Categories : Xml

Powershell - Replace XML content with an environment variable
You need to put the environment variable inside double quotes so it can be expanded. Single quoted strings are not expandable: ... -replace '<Password>(.*?)</Password>', "<Password>$env:HIS_PWD</Password>"

Categories : Xml

Google Docs Viewer - File Request Timeout
If its PDF only, you can also just use pdfjs from Mozilla directly. Then you should check your URL encoding. If the issue remains, check out https://code.google.com/p/google-api-php-client/ for converting your docs in-place. Opening them with pdfjs is still recommended to bypass Google-Doc-Viewer problems, at least that is how I could get this working properly.

Categories : Joomla

Windows Event Viewer holds a lock on my EXE file
There's a less known feature introduced in Vista called Restart Manager that can help you release file locks via a user-mode code. Since you tagged it as C++, based on this article here's a small code sample to do that: #include <RestartManager.h> #pragma comment(lib ,"Rstrtmgr.lib") BOOL ReleaseFileLock(LPCTSTR pFilePath) { BOOL bResult = FALSE; DWORD dwSession; WCHAR szSessionKey[CCH_RM_SESSION_KEY+1] = { 0 }; DWORD dwError = RmStartSession(&dwSession, 0, szSessionKey); if (dwError == ERROR_SUCCESS) { dwError = RmRegisterResources(dwSession, 1, &pFilePath, 0, NULL, 0, NULL); if (dwError == ERROR_SUCCESS) { UINT nProcInfoNeeded = 0; UINT nProcInfo = 0; RM_PROCESS_INFO rgpi[1]

Categories : C++

Powershell Regular Expressions getting values out of a -replace match
Split the string and cast valid values to integers. function doubleIt($digits = "1 2 3 4 5") { #[string](-split $digits -as [int[]] | ForEach-Object {$_*2}) [string](-split $digits | where {$_ -as [int]} | foreach {2*$_} ) }

Categories : Regex

PowerShell Get-Content and replace object in a specific line
Check if a line is starting with a 'Static Text ' followed by a sequence of word characters and return your string in case there a match: Get-Content $OptionsFile | foreach { if($_ -match '^Static Texts+(w+s)+') { 'Static Text MachineX MachineY' } else { $_ } }

Categories : Regex

Extend PowerShell to search/replace and perform on all files in directory?
Try this: import-csv .chapters.csv | ConvertTo-Json -Compress | Foreach {$_ -creplace 'NULL','null'} | Out-File .chapters.json The -replace operators can be used to replace text within a string.

Categories : Powershell

Powershell remote install .exe file errors and not finding setup.iss file
Not sure if you are running into the double-hop problem on not, but it sounds like you are. So I though I'd give you a little more information about it. The Bob Loblaw version. What is a server and what is a client? A server, it accepts things, is the computer you remote onto. A client, it gives things, is the computer you use to do the remoting. So in the command Invoke-Command -computername xxxxxxxxxxx.edu ..., "xxxxxxxxxxx.edu" is the server. From your description, it looks like you already ran the command Enable-PSRemoting on your server. With remoting enabled on the server you should be able to do Enter-PSSession -ComputerName xxxxxxxxxxx.edu and have an interactive command prompt on the client. If you enter a remote session and do Get-ChildItem "\ComputerNameShare" the command is

Categories : Networking

Simple PowerShell Script to loop through 1 CSV file to create a new CSV file from another
Borrowing Shay's awesome CSV field enumeration code: $offices = Import-Csv 'C:path ooffices.csv' Import-Csv 'C:path ousers.csv' | % { foreach ($prop in $_.PSObject.Properties) { $offices | select @{n=$prop.Name;e={$prop.Value}}, OFFICES } } | Export-Csv 'C:path ocombined.csv' -NoTypeInformation

Categories : Powershell

Powershell add newest file in directory to existing file
I will assume you are attempting to get the contents of "C:lah.txt" and add that to "C:lah2.txt"? At the moment you currently get 1 item ("C:Blah.txt") then sort it by last write time, then select 1 (there is only ever one), then add the output to "C:lah2.txt". This will write whatever the regular output is to the file. If you want to write the contents of blah into blah2 you're missing a vital step: Get-ChildItem "C:lah.txt" | sort LastWriteTime | select -last 1 | Get-Content | add-content "C:lah2.txt" After removing redundant calls: Get-ChildItem "C:lah.txt" | Get-Content | add-content "C:lah2.txt" Hope this helps.

Categories : Powershell

Batch file to find a replace a file path in a file
The replacement f, a la FOR ... %v IN (...) DO ... %~fv will resolve the path and make it a fully-qualified path. So, the requirement to get this to work is to get the path to the file(s) in a FOR loop variable. FOR /F "delims=*" %%f IN (list_of_files.txt) DO @ECHO %%~ff As for getting paths from a .CSPROJ file, I don't know the format. Can you say how the paths will be expressed? Are they XML element attributes or content? If they're not easy to find, this will be exceedingly unreliable depending on how the data is expressed.

Categories : Batch File

perl script using XML parser to read values in text file and replace it xml file
A solution using XML::XSH2, a wrapper around XML::LibXML. #!/usr/bin/perl use warnings; use strict; use XML::XSH2; open my $INS, '<', 'install.properties' or die $!; while (<$INS>) { chomp; my ($var, $val) = split / = /; # / fix StackOverflow syntax highlighting. $XML::XSH2::Map::ins->{$var} = $val; } xsh << '__XSH__'; open property.xml ; for /properties/entry { set ./text() xsh:lookup('ins', @key) ; } save :b ; __XSH__ The same programme imlemented using only XML::LibXML: #!/usr/bin/perl use warnings; use strict; use XML::LibXML; open my $INS, '<', 'install.properties' or die $!; my %ins; while (<$INS>) { chomp; my ($var, $val) = split / = /; # / fix StackOverflow syntax highlighting. $ins{$var} = $val; } my $xml =

Categories : Perl

Using Shell script and sed - Find and replace a word in file and rename file
I guess you are making it complex: why not make it simple with two simple satements. Its up to you how you use the below statements for your purpose: perl -pi -e 's/wordtofind/wordtoreplace' your_file #for replacing the word in the file mv your_file wordtoreplace #for renaming the file

Categories : Shell

how to replace a string(after reading file)and store the updated content in a new file?
you can yse regexprep: >> newC = regexprep( file_content, 'hello', 'Ciao' ); >> fid = fopen('newfile.txt', 'wt'); >> fprintf(fid, '%s', newC); >> fclose(fid);

Categories : Matlab

Powershell: Out-File
The pipe only captures the success output stream, not the error and verbose streams. To capture the latter as well you need to redirect it to the former: Move-Item "D:scriptsfileA" "D:scriptsfileB" -Verbose -Force 2>&1 4>&1 | Out-File D:scriptsmove.log -Append See Get-Help about_Redirection for more information.

Categories : Powershell

replace lines from file that match patterns in another file
Iterate through 1.txt and store all values. Then iterate through the lines of 2.txt and if any of the values match any of the values from 1.txt don't store those. Only store values from 2.txt that don't match any from 1.txt.

Categories : Regex

replace patterns in a text file with an update file
This should work: awk -F, ' NR==FNR && NF {a[$0","]++; next} NF {print ($0 in a) ? $0"no change" : $0"new"; delete a[$0]} END {for (x in a) print x"delete"}' old.csv new.csv Output: station,32145,80,no change station,32145,801,new station,32145,60,delete Update based on comments: Handle random . in second column awk 'BEGIN{FS=OFS=","} NR==FNR {gsub(/[.]/,"",$2);a[$0","]++; next} NF {gsub(/[.]/,"",$2); print ($0 in a) ? $0"no change" : $0"new"; delete a[$0]} END {for (x in a) print x"delete"}' old.csv new.csv

Categories : Regex

Powershell Out-file with variable
You are assigning $null to $suspended in your if statement. Use -eq instead to do the comparison: if ($suspended -eq $null) { $user | Out-File -FilePath C:scripts ot_suspended.txt -append -Encoding utf8 }

Categories : Powershell

How do you take file ownership with PowerShell?
Try something like this: $file = Get-Item $path $acl= $file.GetAccessControl() [System.Security.AccessControl.FileSecurity] $acl.SetOwner($newowner) $file.SetAccessControl($acl)

Categories : Powershell

PowerShell Out-file manipulation
You can send your content across the pipeline without writing it out to files. You can use parenthesis to group the output of certain sets of cmdlets and/or functions, and then pipe that output through to the intended cmdlets. This can all be applied on a single line, but I've written it here on multiple lines for formatting reasons. The addition of Out-String is something of a safety measure to ensure that whatever output you're intending to trim can actually be trimmed. Since we're not getting this content from a text file anymore, powershell could possibly return an object that doesn't understand TrimEnd(), so we need to be ready for that. (Get-DistributionGroup | Select-Object Name) | Out-String | Select-Object -Skip 3 | Foreach {$_.TrimEnd()} | Set-Content c:FinalDLGroup.txt

Categories : Powershell

powershell in batch file
Ok, your original script was horribly inefficient and badly designed. Here is the powershell to do what you want, no temp files needed. Normally, I wouldn't have nearly this many comments, but I want to make sure everyone understands what I did. The output files will be in the working directory from where you execute this method. Usage(in cmd/batch): powershell -command "& { . FileContainsThisFunction.ps1; Extract-Hosts original.csv }" Usage(in powershell): . FileContainsThisFunction.ps1; Extract-Hosts original.csv function Extract-Hosts { param( [Parameter(Mandatory=$true)] [String]$InputFile ) if(-not (Test-Path $InputFile)) { throw ("Input file doesn't exist: {0}" -f $InputFile) } # Extract filename without path or extension $BaseName = G

Categories : Powershell

Powershell. Get-content for every file
Your question isn't very clear, if you want to go though every file in the old directory and replace in the contents 'TEST-4' with a random number then output to a new directory then try this: Get-Childitem -Path .old -Filter *.edifact | % { Get-Content $_.FullName | % { $_ -Replace ('TEST-4', (Get-Random).ToString()) } | out-file (Join-Path '. ew' $_.Name) }

Categories : Powershell

How to format the file in powershell
As you are using a string to output the data to the text file you could try the following String formatting to space out the variable in the string evenly. In the example below the spacing is 25 characters between each value: [string]::Format("{0,-25}{1,-25}{2,-25}",$hostIP,$ESXHost,"Success") | Out-File -Append D:CEP estlogging.txt Syntax: $I - This is the parameter number to be inserted (0 or more) $C - The number of total characters before the next variable. (Negative numbers make the word start from the left) [string]::Format("{$I,$C}",Parameter1,Parameter2) There is also a shorthand way of performing the same action using the -f operator: "{0,-25}{1,-25}{2,-25}" -f $hostIP,$ESXHost,"Success" | Out-File -Append D:CEP estlogging.txt

Categories : Powershell

Calling a powershell function using a .bat file
Start Powershell with -command switch, include the script and call the function. You need to dot source the script before its function can be called. :: Create a test script file C: emp>echo function test { write-host "Called from .bat" } > c: emps.ps1 C: emp>powershell -command ". c: emps.ps1; test;" :: Output Called from .bat Also, take a look at some samples.

Categories : Powershell

How to read a line from a file in Powershell
I'm never seen anything from PowerShell, but I mean it can be helpfull for you. What about something like this: foreach ($line in $lines.Split(' ')){ Test-Connection $line.Split(' ')[1] } http://en.wikipedia.org/wiki/Newline

Categories : Powershell

Powershell script to create an xml file
You can try and pipe to the ConvertTo-Xml cmdlet. Here's how the output looks like for 3 process objects. You can then pipe it out to a file : PS> gps | select name,id -first 3 | ConvertTo-Xml -As String -NoTypeInformation <?xml version="1.0"?> <Objects> <Object> <Property Name="Name">AppleMobileDeviceService</Property> <Property Name="Id">1568</Property> </Object> <Object> <Property Name="Name">audiodg</Property> <Property Name="Id">5140</Property> </Object> <Object> <Property Name="Name">Babylon</Property> <Property Name="Id">4908</Property> </Object> </Objects>

Categories : SQL

Best way to assemble a string file in PowerShell
I would use a single here-string: $metadata = @" <xml> <targets> $( foreach ($resolution in $resolutions) { "<target>" "<bitrate>$($resolution.bitrate)</bitrate>" "<width>$($resolution.width)</width>" "<height>$($resolution.height)</height>" "</target>" } ) </targets> </xml> "@ $metadata | out-file Metadata.xml -encoding ASCII

Categories : Powershell

Convert HTML file into .CSV using powershell
Here is the beginning of a solution, not so good ... It supposes that HtmlAgilityPack.dll is in Html-Agility-Pack directory of the directory script file. Add-Type -Path "$(Split-Path -parent $PSCommandPath)Html-Agility-PackHtmlAgilityPack.dll" $webGraber = New-Object -TypeName HtmlAgilityPack.HtmlWeb $webDoc = $webGraber.Load("C: emp .htm") $trDatas = $webDoc.DocumentNode.ChildNodes.Elements("tr") Remove-Item "c: emp .csv" foreach ($trData in $trDatas) { $tdDatas = $trData.elements("td") $line = "" foreach ($tdData in $tdDatas) { $line = $line + $tdData.InnerText.Trim() + ',' } $line.Remove($line.Length -1) | Out-File -FilePath "c: emp .csv" -Append }

Categories : HTML

powershell - extract file type from zip
You need to iterate over the contents checking if the file extension of each item is ".zip" before extracting. Something like this should work: $shell = new-object -com shell.application $zip = $shell.NameSpace(“C:howtogeeksite.zip”) foreach($item in $zip.items()){ if([System.IO.Path]::GetExtension($item.Path) -eq ".zip"){ $shell.Namespace(“C: emphowtogeek”).copyhere($item) } }

Categories : Powershell

Search a file in 4 different path using powershell
Try: $p = "C:Program Files est1", "C:Program Files est3", "C:Program Files (x86) est6", "D:" Get-ChildItem -Path $p -Filter file.txt -Recurse | select directory | ac C:filereport.txt

Categories : Search

Powershell TCP Send Entire File
I can only guess, but it may be related to the server code?! recv_length = 1024 EDIT: You could try a close of the stream, maybe that is the problem?! $stream.write($test,0,$test.Length); $stream.close(); $writer.flush();

Categories : C#

Copy/transfer file using PowerShell 2.0
One of the nice things about PowerShell is (unlike DOS) it support UNC paths. So you can literary just do: Copy-Item -Path <local file path> -Destination \<server IP><share><path> Of course your account will need to have access to that location. If you need to enter alternate credentials you can pre-authenticate using net use \<server IP><share> /user:[<domain>]<user> <password>

Categories : Powershell



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.