Can anyone tell me why this opens instead of sends the file?
$d = [DateTime]::Today.AddDays(-90)
Get-ADComputer -Filter 'lastLogon -le $d' -Properties lastLogon |
Export-Csv c:\temp\stale_servers.csv
If (c:\temp\stale_servers.csv = $?)
{
Send-MailMessage -SmtpServer xxxxxxxxx -To xxxxxxxxx -From xxxxxx -Subject "test mail" -Body "The servers that have not logged in, in the past 90 days are attached." -attachment c:\temp\stale_servers.csv
}
I think the issue is in this line:
If (c:\temp\stale_servers.csv = $?)
if you want to test the existence of the file use:
If (test-path -path "c:\temp\stale_servers.csv" )
Related
I am adding 200+ hyperlinks to an excel file for easier access to sharepoint folders. Rather than manually pulling each one I am trying to bulk export the file paths from a sharepoint folder. Any ideas on how to do this?
We can use PnP PowerShell to achieve it.
#Config Variables
$SiteURL = "https://tenant.sharepoint.com/sites/lz"
$ListName = "DL0906"
$FolderRelativeURL= "/sites/lz/DL0910/Test"
$ExportFile="C:\temp\FileUrls.csv"
#Get Credentials to connect
$Cred = Get-Credential
Try {
#Connect to PNP Online
Connect-PnPOnline -Url $SiteURL -Credentials $Cred
#Get All Items from the Folder
$CAMLQuery = "<View Scope='RecursiveAll'><Query><Where><Eq><FieldRef Name='FileDirRef'/><Value Type='Text'>$FolderRelativeURL</Value></Eq></Where></Query></View>"
$FolderItems = Get-PnPListItem -List $ListName -Query $CAMLQuery
$FileCollection = #()
ForEach($Item in $FolderItems)
{
$ExportFileUrl = New-Object PSObject
$ExportFileUrl | Add-Member -MemberType NoteProperty -name "File URL" -value $Item["FileRef"]
$FileCollection += $ExportFileUrl
}
$FileCollection | Export-CSV $ExportFile -NoTypeInformation
}
catch {
write-host "Error: $($_.Exception.Message)" -foregroundcolor Red
}
Refer to: SharePoint Online: Get All Files from a Folder using PowerShell
I am trying to create registry entries for some time now.
Enviroment:
Offline environment (No Domain)
1 Windows Server 2012 R2
200 Windows 7 clients
The following entry should be created on several computers:
[HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\system]
"LocalAccountTokenFilterPolicy"=dword:00000001
For this I would like to use the following script
$Computers = Get-Content "C:\Scripts\Clients.txt"
$Path = "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System"
$Name = "LocalAccountTokenFilterPolicy"
$PropertyType = "DWord"
$Value = 1
$results = foreach ($computer in $Computers) {
if (Test-Connection -ComputerName $computer -Count 1 -Quiet) {
try {
Set-ItemProperty -Path $path -Name $Name -Value $Value -Type $PropertyType -ErrorAction 'Stop'
$status = "Success"
} catch {
$status = "Failed"
}
} else {
$status = "Unreachable"
}
New-Object -TypeName PSObject -Property #{
'Computer' = $computer
'Status' = $status
}
}
$results | Export-Csv -NoTypeInformation -Path "./error.csv"
The script is executed, no error appears, but the entries were not created.
Where is my error?
Always try a simple 'Get' first, and then progress to testing lines before trying your 'Set'...
So you first test locally on a system, before your foreach invoke, on single system:
`Get-ItemProperty HKLM:SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System -Name LocalAccountTokenFilterPolicy`
If you get a good response like this:
LocalAccountTokenFilterPolicy : 0
PSPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\Curre
ntVersion\Policies\System
PSParentPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\Curre
ntVersion\Policies
PSChildName : System
PSDrive : HKLM
PSProvider : Microsoft.PowerShell.Core\Registry
Then you've got the right command to work with. Now change the 'Get' to a 'Set' and work out the values LOCALLY.
I think you are close, but missed something in your tests...
Do ONE at a time, locally, first in PowerShell ISE. Then invoke-command to that same single system, then one by one add your tests...
- Patrick Burwell, 25 year Windows and Linux SysAdmin
I received a request to run this on each of my systems which pulls a list of installed applications and outputs it into a text file. I then have to combine all of these things into something more readable which will take a while. I am learning Powershell and want to make this be executed from one system, pull from a list of servers in a text file and run this query from one place against all of the systems:
Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* | Select-Object DisplayName, DisplayVersion, Publisher, InstallDate | Format-Table –AutoSize > "$Env:userprofile\desktop\Installed Programs for $env:computername.txt"
I've started working on it but am thinking I am missing something to get this to work. I am currently piping this to a string to then output to a csv (I am open to suggestions). This is what I have so far.
# Computer running this script
$WhoAmI = $env:ComputerName
$ServerList = get-content -path "C:\scripts\ServerList.txt"
$Path = "C:\scripts\results"
foreach ($server in $ServerList)
{
$InstalledApps = Invoke-Command -ComputerName $server {Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* }
$Results += $InstalledApps |
Select-Object DisplayName, DisplayVersion, Publisher, InstallDate |
Out-String
}
Write-Host $InstallApps
# $InstallApps | export-csv "$Path\InstalledFiles.csv"
I currently am testing the functionality of the loop by just trying to get it to write to the screen. I only get a blank response.
You weren't getting output because you used the (undefined) variable $InstallApps instead of the variable $results.
With that said, I wouldn't recommend doing string concatenation in a loop. Something like this would be a more elegant approach:
Get-Content -Path 'C:\scripts\ServerList.txt' | ForEach-Object {
$server = $_
Invoke-Command -ComputerName $server -ScriptBlock {
Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*
} | Select-Object #{n='Server';e={$server}}, DisplayName, DisplayVersion,
Publisher, InstallDate
} | Export-Csv 'C:\scripts\results\InstalledPrograms.csv' -NoType
I kind of figured it out. Rested eyes on a fresh day. Some mistakes in what I am writing out, etc. I am open to improvements if anyone has anything to contribute.
EDIT: I got it working mostly with the following but the output is messy. Open to suggestions.
# Computer running this script
$ServerList = get-content -path "C:\scripts\ServerList.txt"
$Path = "C:\scripts\results"
foreach ($server in $ServerList)
{
$Results += "Results for $server"
$InstalledApps = Invoke-Command -ComputerName $server -ScriptBlock {Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* }
$Results += $InstalledApps |
Select DisplayName, DisplayVersion, Publisher, InstallDate |
Out-String
}
# Write-Host $Results
$Results | out-file -filepath "$Path\InstalledPrograms.txt" -width 200
How could i upload a log file from my local system to a webpage (http://abc..) using powershell script?
Thanks in advance
If you are using HTTP, try something like this:
$sourceFilePath = "c:\MyLocalFolder\LocalLogFileName.log"
$siteAddress = "http://192.168.15.12/DestinationFolder"
$urlDest = "{0}/{1}" -f ($siteAddress, "DestinationLogFileName.log";
$webClient = New-Object System.Net.WebClient;
$webClient.Credentials = New-Object System.Net.NetworkCredential("MyUserName", "MyPassword");
("*** Uploading {0} file to {1} ***" -f ($sourceFilePath, $siteAddress) ) | write-host -ForegroundColor Green -BackgroundColor Yellow
$webClient.UploadFile($urlDest, "PUT", $sourceFilePath);
I am having the following problem.
I have a powershell script to send me emails with log files attached.
The only problem is that I need only the log files that are not empty.
So i have tried to use this script:
If ((Get-content "Log.txt") -gt 0 ) {
$smtp.Send($msg)
echo "email sent"
} else {
echo "File is blank"
}
It seems that -gt 0 is not working for me.
No matter what I have tried powershell still sends me the empty logs.
So can you please show me where I am wrong?
I have tried this as well:
If ((Get-Content $file) -eq $Null) {
"File is blank"
} else {
$smtp.Send($msg)
echo "email sent"
}
But it is still not working.
Thank you in advance.
Get-Content will read the entire contents of the file - only to throw it all away! That's a huge waste of resources.
Instead, get info from the fileystem itself about the file with get-item or get-childitem.
if ((get-item "log.txt").length -gt 0) {
do stuff
}
It also looks like you're using an antiquated method of sending email. In PowerShell 2.0 and above, use Send-MailMessage - it's much easier to use. In fact, if you have all the logfiles in one directory, you can distill this to a two-liner:
$logs = get-childitem -path PATH_TO_LOGS|where-object{($_.length -gt 0) -and !$_.PSIsContainer}|select-object -expandproperty fullname
Send-Mailmessage -attachments $logs OTHER_PARAMETERS_HERE