How to write the console output from powershell to a text file - powershell

I have tried many solutions to get the output of powershell to a text file so I can read it. I can't get the console output to stop at the end so I can read it and I can't get it to write out a file. With this code a text file isn't written. Windows 10 1903
:: This will Remove all Appxpackages
::
$AppsList = 'Microsoft.3DBuilder',
'Microsoft.BingFinance',
'Microsoft.BingNews',
'Microsoft.BingSports',
'Microsoft.MicrosoftSolitaireCollection',
'Microsoft.People',
'Microsoft.Windows.Photos',
'Microsoft.WindowsCamera',
'microsoft.windowscommunicationsapps',
'Microsoft.WindowsPhone',
'Microsoft.WindowsSoundRecorder',
'Microsoft.XboxApp',
'Microsoft.ZuneMusic',
'Microsoft.ZuneVideo',
'Microsoft.Getstarted',
'Microsoft.WindowsFeedbackHub',
'Microsoft.XboxIdentityProvider',
'Microsoft.MicrosoftOfficeHub',
'Fitbit.FitbitCoach',
'ThumbmunkeysLtd.PhototasticCollage'
C:\Batch\PSEXEC.EXE -s powershell -c
Start-Transscript -Path 'C:\RemoveAllAppxPackages.txt'
ForEach ($App in $AppsList){
$PackageFullName = (Get-AppxPackage -AllUsers $App).PackageFullName
$ProPackageFullName = (Get-AppxProvisionedPackage -AllUsers | where {$_.Displayname -eq $App}).PackageName
write-host $PackageFullName
Write-Host $ProPackageFullName
if ($PackageFullName){
Write-Host "Removing Package: $App"
remove-AppxPackage -package $PackageFullName -AllUsers > C:\RemoveAllAppxPackages.txt
) pause
}
else{
Write-Host "Unable to find package: $App" > C:\RemoveAllAppxPackages.txt
pause
}
if ($ProPackageFullName){
Write-Host "Removing Provisioned Package: $ProPackageFullName"
Remove-AppxProvisionedPackage -online -packagename $ProPackageFullName > C:\RemoveAllAppxPackages.txt
pause
}
else{
Write-Host "Unable to find provisioned package: $App" > C:\RemoveAllAppxPackages.txt
pause
}
}
Pause
Stop-Transcript

Instead of your write-host line, you could just write the bits you need in the file (wrap in quotes) and then pipe to out-file to a txt file. eg.
"Unable to find package: $App" | Out-File -FilePath C:\path\to\file.txt -Append
Note, make sure you add -append otherwise the file will be overwritten each time.

You have a typo in the Start-Transcript command.....
Start-Transscript -Path 'C:\RemoveAllAppxPackages.txt'
Should read
Start-Transcript -Path 'C:\RemoveAllAppxPackages.txt'

Related

PowerShell Verbose-Parameter

I have a few questions about the verbose-parameter.
Example script:
try {
New-Item -Path "C:\Test.txt" -ItemType "File" -ErrorAction Stop -Verbose
}
catch {
Write-Host $Error[0]
}
Output:
VERBOSE: Execute the "Create file" operation for the target "Target: C:\Test.txt".
Access to the path "C: \ Test.txt" was denied.
How do I save the verbose message in a variable?
Is it possible to edit the verbose message automatically generated by PowerShell before saving it in a log file (add date and time)?
Example script (not working):
try {
New-Item -Path "C:\Test.txt" -ItemType "File" -ErrorAction Stop -Verbose *> $LogFile
}
catch {
Write-Host $Error[0]
}
Are there better suggestions to write a "success" log file than with the parameter verbose and without having to write it manually?
Thank you!
You can assign the verbose output to a variable if you merge the Verbose stream into standard output stream (4>&1):
$output = New-Item "C:\Test.txt" -ItemType "File" -ErrorAction Stop -Verbose 4>&1
Since New-Item also returns the newly created file, you'll want to split the output into verbose vs normal again:
$verboseOutput,$normalOutput = $output.Where({$_ -is [System.Management.Automation.VerboseRecord]}, 'Split')
And now you can prepend timestamps to the records in $verboseOutput before writing them to disk

Powershell move files to a new folder that are not still writing to the source folder

I have a powershell script that's moving files from a source directory over to a target directory every 15 minutes. Files of around 1 meg are moving into the source directory by an SFTP server... so the files can be written at anytime by the SFTP clients.
The Move-Item command is moving files, however it seems that it's moving them without making sure the file isn't still being written (in-use?).
I need some help coming up with a way to write the files from the source to the target and make sure the entire file gets to the target. Anyone run across this issue before with Powershell?
I searched and was able to find a few functions that said they solved the problem but when I tried them out I wasn't seeing the same results.
Existing PowerShell script is below:
Move-Item "E:\SFTP_Server\UserFolder\*.*" "H:\TargetFolder\" -Verbose -Force *>&1 | Out-File -FilePath E:\Powershell_Scripts\LOGS\MoveFilesToTarget-$(get-date -f yyyy-MM-dd-HH-mm-ss).txt
I ended up cobbling together a few things and got this working as I wanted it. Basically I'm looping through the files and checking the length of the file once... then waiting a second and checking the length of the file again to see if it's changed. This seems to be working well. Here's a copy of the script incase it helps anyone in the future!
$logfile ="H:\WriteTest\LogFile_$(get-date -format `"yyyyMMdd_hhmmsstt`").txt"
function log($string, $color)
{
if ($Color -eq $null) {$color = "white"}
write-host $string -foregroundcolor $color
$string | out-file -Filepath $logfile -append
}
$SourcePath = "E:\SFTP_Server\UserFolder\"
$TargetPath = "H:\TargetFolder\"
$Stuff = Get-ChildItem "$SourcePath\*.*" | select name, fullname
ForEach($I in $Stuff){
log "Starting to process $I.name" green
$newfile = $TargetPath + $I.name
$LastLength = 1
$NewLength = (Get-Item $I.fullname).length
while ($NewLength -ne $LastLength) {
$LastLength = $NewLength
Start-Sleep -Seconds 1
log "Waiting 1 Second" green
$NewLength = (Get-Item $I.fullname).length
log "Current File Length = $NewLength" green
}
log "File Not In Use - Ready To Move!" green
Move-Item $I.fullname $TargetPath
}

writing output file as .txt or .csv to script containing multiple conditions

I have written a script which checks a service status, tests two paths and also tests a registry value. Currently I am getting output on the power shell console (that could be because I am using write-output command).
Is there any way to write the single one page output to a file?
I am struggling to find a way to out-file entire output to a file.
Below is the script.
$testpath = Test-Path "C:\test"
$testpath2 = test-path "C:\test"
$mcshieldk = Get-Service -Name mcshield | select Name
$internet = (Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\internet explorer").MkEnabled $hostname = hostname Write-Host "hostname of comuter is" $hostname if (Test-Path $Machinetype)
{}
else { Write-Host "internet is" $internet }
if ($testpath -eq $true -and $testpath2 -eq $true)
{ Write-Host "test and test1 folder exists" -ForegroundColor Green }
else{ Write-Host "folder does not exists" -ForegroundColor Red } if($mcshield.Name -eq "mcshield") { Write-Host "mcshield service exists" }
else { Write-Host "mcshield does not exists" }
Below is the console output
hostname of comuter is Server1
internet is Yes
test and test1 folder exists
mcshield does not exists
Swap out your Write-Host cmdlets or add in another line with the following:
"Your output text $YourVariable" | Out-File -FilePath "C:\Log.txt" -Append -Encoding utf8
This will append a string to the end of the log file C:\Log.txt. Note, missing the -Append parameter will cause the file to be overwritten.
You can also use the follow to give the same affect:
"Your output text $YourVariable" >> "C:\Log.txt"
But be carefully not to mix the two methods as you might get encoding errors in the text file. If you wish to overwrite the file with the second method use > instead of >>.

want to see a message on powershell ISE while executing .exe

I am trying to execute this powershell script
Write-output `n "\\Latest Modified Mobile file is"
$dir = "\\sharepoint.amr.ith.intel.com#SSL\sites\peca\PTA Data Sandbox\Shared Documents\Under_review\Regina\Estimates"
$filter="*EstimateImport_Mobile_*.xlsx"
$latest = Get-ChildItem -Path $dir -Filter $filter | Sort-Object LastAccessTime -Descending | Select-Object -First 1
$latest.Name
if($?)
{
"command succeeded"
}
else
{
"command failed"
}
& "C:\PECA Data Estimates Importer\PECA Estimates Importer.exe" import -i $latest.FullName
if($?)
{
"command succeeded"
}
else
{
"command failed"
}
Start-Sleep -s 5
exit
when I am using the "&" operator, it runs some windows .exe tool but on the screen I don't see any message, I want to see a message like "Running tool" on a powershell ISE so that the user knows that the script is still working.
If you want to see output on the screen, don't use Write-Output.
Use Write-Host to write text that will always be seen. Use Write-Verbose to write text that will only be seen in verbose mode.

Pipe all Write-Output to the same Out-File in PowerShell

As the title suggests, how do you make it so all of the Write-Outputs - no matter where they appear - automatically append to your defined log file? That way the script will be nicer to read and it removes a tiny bit of work!
Little example below, id like to see none of the "| Out-File" if possible, yet have them still output to that file!
$Author = 'Max'
$Time = Get-Date -Format "HH:mm:ss.fff"
$Title = "Illegal Software Removal"
$LogName = "Illegal_Remove_$($env:COMPUTERNAME).log"
$Log = "C:\Windows\Logs\Software" + "\" + $LogName
$RemoteLog = "\\Server\Adobe Illegal Software Removal"
Set-PSBreakpoint -Variable Time -Mode Read -Action { $global:Time = Get-Date -format "HH:mm:ss.fff" } | Out-Null
If((Test-Path $Log) -eq $False){ New-Item $Log -ItemType "File" -Force | Out-Null }
Else { $Null }
"[$Time][Startup] $Title : Created by $Author" | Out-File $Log -Append
"[$Time][Startup] Configuring initial variables required before run..." | Out-File $Log -Append
EDIT: This needs to work on PS v2.0, I don't want the output to appear on screen at all only in the log. So I have the same functionality, but the script would look like so...
"[$Time][Startup] $Title : Created by $Author"
"[$Time][Startup] Configuring initial variables required before run..."
You have two options, one is to do the redirection at the point the script is invoked e.g.:
PowerShell.exe -Command "& {c:\myscript.ps1}" > c:\myscript.log
Or you can use the Start-Transcript command to record everything (except exe output) the shell sees. After the script is done call Stop-Transcript.