how to overwrite file content with power shell - powershell-2.0

I am new to powershell. how do you over write file in powershell? write now below code is appending. I want to completely over write file with below new info.
$someinfo | Add-Content $FileName

Use Set-Content instead of Add-Content.
Difference between Set-Content and Add-Content:
Add-Content=> Append
Set-Content=> replace content
Reference:
https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/set-content?view=powershell-5.1

You can do an Out-File as well
'Some content' | Out-File -FilePath c:\windows\temp\file.log

Related

PowerShell - Problems Passing Variables into ForEach Loop

I am trying to enumerate a list of servers from Active Directory, and then insert the server name into a UNC path as part of a copy command.
When I execute the script, I get the result below. I think that maybe I have to convert my variable, but I am not sure what to convert it to.
VERBOSE: Performing the operation "Copy File" on target "Item: C:\davidtemp\Logo.png Destination: \#{name=NCIDITSTWEB07}\c$\program files...
$webdev = Get-ADOrganizationalUnit -filter {name -like "*dev*"} | where {$_.DistinguishedName -like "*relativity*"}
$ServerList = Get-ADComputer -SearchBase $webdev | where {$_.name -like "*web*"} | select name | sort name
Foreach($server in $ServerList)
{
$scriptBlockwork = { copy C:\davidtemp\Logo.png "\\$server\c$\program files\web\images" -Force -Verbose}
Invoke-Command -ScriptBlock $scriptBlockwork -verbose
}
I reached out to a friend who was able to help. I was not defining the variable properly.
I needed to use -expandProperty to get the results into a format that worked with the pipeline
$ServerList = Get-ADComputer -SearchBase $webdev | where {$_.name -like "web"} | select -expandProperty name
Hopefully this helps someone else who might be having a similar issue.

PowerShell Select-String option

Using the Select-String cmdlet:
Get-Content C:\Temp\PatchVerify\$env:ComputerName.csv | Select-String "UNKNOWN" -quiet
Once all "Unknown" strings are found what options can I add to delete those strings?
If you're trying to do what I think you're trying to then try this code:
$file = Get-Content "C:\Temp\PatchVerify\$env:ComputerName.csv" | ForEach-Object {$_ -replace "UNKNOWN",""}
Set-Content C:\Temp\test.txt "C:\Temp\PatchVerify\$env:ComputerName.csv"
Get the content of your file as a variable
Pipe the output to a replace operator for each occurrence of the "UNKNOWN" string
Assign the result to a variable
Use the Set-Content cmdlet to save the variable as your new file

POWERSHELL: Drop X number of beginning characters in a file

I have a vendor-propriety files that I am converting to csv. I need to delete the first 7 characters of each file. These characters are a mix of printable and non-printable characters.
For example, the one file might have
$([char]0x56)$([char]0x28)$([char]0x00)$([char]0x00)$([char]0x4C)$([char]0x01)$([char]0x01)
And the next file might have
$([char]0x4F)$([char]0xE7)$([char]0x00)$([char]0x00)$([char]0x4C)$([char]0x01)$([char]0x01)
And the next file might have something completely different.
Even simpler:
(Get-Content <CSV file path> | Out-String).Substring(7) | Out-File <CSV file path>
To do this for all CSV files in a directory:
gci <path to directory>\*.csv | (Get-Content $_ | Out-String).Substring(7) | Out-File $_

Powershell: Count items in a folder with PowerShell

I'm trying to write a very simple PowerShell script to give me the total number of items (both files and folders) in a given folder (c:\MyFolder). Here's what I've done:
Write-Host ( Get-ChildItem c:\MyFolder ).Count;
The problem is, that if I have 1 or 0 items, the command does not work---it returns nothing.
Any ideas?
You should use Measure-Object to count things. In this case it would look like:
Write-Host ( Get-ChildItem c:\MyFolder | Measure-Object ).Count;
or if that's too long
Write-Host ( dir c:\MyFolder | measure).Count;
and in PowerShell 4.0 use the measure alias instead of mo
Write-Host (dir c:\MyFolder | measure).Count;
I finally found this link:
https://blogs.perficient.com/microsoft/2011/06/powershell-count-property-returns-nothing/
Well, it turns out that this is a quirk caused precisely because there
was only one file in the directory. Some searching revealed that in
this case, PowerShell returns a scalar object instead of an array.
This object doesn’t have a count property, so there isn’t anything to
retrieve.
The solution -- force PowerShell to return an array with the # symbol:
Write-Host #( Get-ChildItem c:\MyFolder ).Count;
If you need to speed up the process (for example counting 30k or more files) then I would go with something like this..
$filepath = "c:\MyFolder"
$filetype = "*.txt"
$file_count = [System.IO.Directory]::GetFiles("$filepath", "$filetype").Count
Only Files
Get-ChildItem D:\ -Recurse -File | Measure-Object | %{$_.Count}
Only Folders
Get-ChildItem D:\ -Recurse -Directory | Measure-Object | %{$_.Count}
Both
Get-ChildItem D:\ -Recurse | Measure-Object | %{$_.Count}
You can also use an alias
(ls).Count
Recursively count files in directories in PowerShell 2.0
ls -rec | ? {$_.mode -match 'd'} | select FullName, #{N='Count';E={(ls $_.FullName | measure).Count}}
In powershell you can to use severals commands, for looking for this commands digit: Get-Alias;
So the cammands the can to use are:
write-host (ls MydirectoryName).Count
or
write-host (dir MydirectoryName).Count
or
write-host (Get-ChildrenItem MydirectoryName).Count
To count the number of a specific filetype in a folder.
The example is to count mp3 files on F: drive.
( Get-ChildItme F: -Filter *.mp3 - Recurse | measure ).Count
Tested in 6.2.3, but should work >4.

PowerShell command to parameterised PowerShell function?

I'm not so hot with PowerShell yet, but have managed to get this command to work quite nicely:
get-childitem "C:\Code\WC1" -Recurse | select-string "insert into\s+my_table"
Thing is, I know I'm going to struggle to remember this, so how can I make it into a function where the path supplied to get-childitem and the search regex are parameters?
I'm using PowerShell 2.0.
more commonly these days the parameters are being called after the function declaration e.g.
Function Find-Code {
param([string] $path, [string] $pattern)
get-childitem $path -Recurse | select-string $pattern
}
Function Find-Code([string] $path, [string] $pattern)
{
get-childitem $path -Recurse | select-string $pattern
}
You can put this in your PowerShell Profile.
An easy way to do this is to edit the $profile file (run something like notepad $profile from your PowerShell prompt) and just paste the text right in.

Resources