Trying to get random line, store it, then delete it

Title loosely explains my goal…

 

Have a document with random information inside. I want to grab it, store it in a variable, then remove it from the document. I’ve seen on this forum and other posts most people mention it’s best to just re-save the document without the information that was grabbed. I’ve attempt to get it to work for my purpose, but it’s not really coming through the right way.

 

Random.txt
1
2
3
4

$Number = Get-Random -InputObject (get-content C:\Scripts\random.txt)

# The below is what isn't working for me... it keeps clearing everything out no matter what I use... #
get-content C:\Scripts\random.txt | where { $_ -ne "$number" } | Out-File C:\Scripts\random.txt

 

For example, I run it. I get 3. Then it re-saves the document. The next available options within the document are 1, 2, and 4. Rinse and repeat as long as I want.

It seems to work if I make it a new file name, but the point is to keep the list intact as it is.

 

Thanks in advance.

You are doing everything in the same pipeline and it’s keeping the file open and then you are trying to write to it while Get-Content has it open.

PS C:\Users\rasim> get-content C:\Scripts\random.txt | 
where { $_ -ne "$number" } |
Set-Content C:\Scripts\random.txt
Set-Content : The process cannot access the file 'C:\Scripts\random.txt' because it is being used by another process.
At line:3 char:1
+ Set-Content C:\Scripts\random.txt
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Set-Content], IOException
    + FullyQualifiedErrorId : System.IO.IOException,Microsoft.PowerShell.Commands.SetContentCommand

Back in VBSCript days when you opened a file, you had to specify a mode to open the file or it would open in Read-Only locked mode. Just move the SET of the content out of the pipeline:

$content = get-content C:\Scripts\random.txt | 
           where { $_ -ne "$number" }

$content | Out-File C:\Scripts\random.txt

[quote quote=244325] Just move the SET of the content out of the pipeline:
[/quote]

Thanks!

It should be possible to do it in the pipeline as well with a slight tweak.

(Get-Content $file) | ForEach-Object {$_ -replace '%','percent'} | Set-Content $file

This grabs the content of the file and unloads it - that’s the reason for the parenthesis, the Foreach-Object then iterates over the content of the file and saves it to the same file name as before, all in the pipeline.

Thanks for sharing KLaage. Thought it was interesting that it even kept the file open when you couldn’t use Set-Content or something to write back to it, but when in doubt Please Excuse My Dear Aunt Sally (PEMDAS) :slight_smile: