Powershell Get-EventLog System -After -Before from remote nodes - get-eventlog

I'm trying to get the EventLog systems from a list of nodes; I'm using psexec
 and Get-EventLog.
I would like to speed up the procedure by adding the After and Before parameters that I would like to read from a file.
This is the piece of code that runs on the server:
#$Da = Pick-Date -testo "DATA INIZIO?"
#$Da | Out-File $localDir\GetEventLog.da.txt
#$Al = Pick-Date -testo "DATA FINE?"
#$Al | Out-File $localDir\GetEventLog.al.txt
foreach ($node in Get-Content $localDir\GetEventLog.input.txt)
{
    net use N: $node\c$ $pwd /user:$node\administrator
    mkdir N:\GetEventLog\
    copy $localDir\GetEventLog.cmd N:\GetEventLog\
    copy $localDir\GetEventLog.ps1 N:\GetEventLog\
# copy $localDir\GetEventLog.da.txt N:\GetEventLog\
# copy $localDir\GetEventLog.al.txt N:\GetEventLog\
    psexec $node C:\GetEventLog\GetEventLog.cmd
    copy N:\GetEventLog\System.* $localDir\
    net use N: /delete
    pause
}
This is the one running on clients:
$wrkDir = "c:\GetEventLog"
$filenameFileOutput = "$wrkDir\System." + $(hostname) + ".txt"
Get-EventLog System | Out-File -Width 200 $filenameFileOutput
I can't pass the contents of the GetEventLog.da.txt and GetEventLog.al.txt files as parameters to Get-EventLog.
Thanks

Related

Terraform - Azure - azurerm_virtual_machine_extension - multiline Powershell script

I am preparing VM deployment, and on VMs I need to run some powershell command lets. I need to install Windows Server role, and initialize new ssd disk. I am working on Azure cloud, Terraform deployment has been tested, works as expected, VM is deployed with all required configuration, but facing some problems during multiline powershell commands. I use terraform resource azurerm_virtual_machine_extension, it works when I am trying to install/use one block of code, for example for Windows server role installation. I don't want to use storage account and container and .ps1 script file uploaded to storage container, I need to use inline powershell code. My terraform clode below.
resource "azurerm_virtual_machine_extension" "vmext" {
name = "vmext"
virtual_machine_id = azurerm_windows_virtual_machine.app_vm.id
publisher = "Microsoft.Compute"
type = "CustomScriptExtension"
type_handler_version = "1.10"
settings = <<SETTINGS
{
"commandToExecute": "powershell -ExecutionPolicy Unrestricted Install-windowsfeature -name RoleName -IncludeManagementTools; powershell -ExecutionPolicy Unrestricted Get-Disk | Where-Object -FilterScript {$_.PartitionStyle -eq 'RAW'} | Initialize-Disk -PartitionStyle MBR -PassThru | New-Partition -AssignDriveLetter -UseMaximumSize | Format-Volume -FileSystem NTFS -NewFileSystemLabel 'disk2' -Confirm:$false"
}
SETTINGS
}
Try this:
resource "azurerm_virtual_machine_extension" "vmext" {
name = "vmext"
virtual_machine_id = azurerm_windows_virtual_machine.app_vm.id
publisher = "Microsoft.Compute"
type = "CustomScriptExtension"
type_handler_version = "1.10"
settings = <<SETTINGS
{
"commandToExecute": <<EOF
powershell -ExecutionPolicy Unrestricted Install-windowsfeature -name RoleName -IncludeManagementTools
powershell -ExecutionPolicy Unrestricted Get-Disk | Where-Object -FilterScript {$_.PartitionStyle -eq 'RAW'} | Initialize-Disk -PartitionStyle MBR -PassThru | New-Partition -AssignDriveLetter -UseMaximumSize | Format-Volume -FileSystem NTFS -NewFileSystemLabel 'disk2' -Confirm:$false"
EOF
}
SETTINGS
}
Hope this helps!

Bulk Export file paths from sharepoint

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

Creating registry DWORD entry with 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

How do I turn this simple command into something that loops from a list of remote systems?

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

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.

Resources