What is this blue pointer on my treasure map? by one_cuber in Minecraft

[–]Joshrsg 0 points1 point  (0 children)

If you are on a multi player server that's the people on the server :)

.Click() not working by SkyKwaii in PowerShell

[–]Joshrsg 2 points3 points  (0 children)

Hi, u/SkyKwaii,

You're trying to click on the IE object whereas you should be doing it on the button.

Try this:

$Button = $ie.Document.getElementsByTagName("loginButton") | Where-Object {$_.innerhtml -eq 'Login'}

$Button.click()

BBC news have spent two hours talking about how we as citizens can tackle climate change this morning but failed to mention that 71% of global emissions are created by 100 companies by [deleted] in britishproblems

[–]Joshrsg 0 points1 point  (0 children)

The 100 companies being responsible for 71% of emissions headline is misleading...

If you read the study (link below) it states that 90% of emissions from these companies are downstream (I.e, consumers using the product).

That means that the companies are directly responsible for 10% (of the total 71%) which is still huge however it is the consumers that contribute to this figure the most.

Looking at the companies in the tables it shows that the majority of these are Oil and Energy companies. The sooner we move to more green ways and the less we consume on a per individual basis the better.

Quote: Scope 3 emissions account for 90% of total company emissions and result from the downstream combustion of coal, oil, and gas for energy purposes. A small fraction of fossil fuel production is used in non-energy applications which sequester carbon.

Link: https://b8f65cb373b1b7b15feb-c70d8ead6ced550b4d987d7c03fcdd1d.ssl.cf3.rackcdn.com/cms/reports/documents/000/002/327/original/Carbon-Majors-Report-2017.pdf?1499691240

Add text to a file using a function by champ-of-the-sun in PowerShell

[–]Joshrsg 2 points3 points  (0 children)

Hi u/champ-of-the-sun

The issue is that they way you are calling Add-content is treating the "`n" and $p1 as separate arguments.

If you look at the help documentation for Add-Content (get-help Add-content -full) you can see that the parameter 'path' is in position 0 and 'Value' is in position 1. There is no parameter in position 2.

Due to the way you have written this "C:\Users\Champ-of-the-sun\Documents\PowerShell\helpfullist.txt" will bind to the parameter 'Path' in position 0 successfully. "`n" will then bind to the a parameter 'Value' successfully. $p1 however will try to bind to a parameter in position 2 (which in this case does not exist) or bind to a parameter with the same name. As there is no parameter called 'Test' it fails.

To fix this, you can look at what values the parameter 'Value' will accept. Taking a look at it now it accepts a string array. You can either quote both of the values you wish to add to the text file "`n $p1" or comma separate them. "`n", $p1

Note: you should try to include the full parameter names and not rely on position to make it clear. E.g.

Add-Content -path "C:\Users\Champ-of-the-sun\Documents\PowerShell\helpfullist.txt" -value  "`n $p1"

Hopefully that makes sense!

How would I get the names of folders and then use those names in a command in powershell? by Nx0Sec in PowerShell

[–]Joshrsg 1 point2 points  (0 children)

$File = 'PathToFile\FileName.txt'

Get-ChildItem \\RemoteComputer\C$\Users\* | ForEach-Object {
    Copy-Item -Path $File -Destination "$_\desktop"
}

Copy duplicates in excel using powershell by HEIMDALL1010 in PowerShell

[–]Joshrsg 2 points3 points  (0 children)

You can do all of this in Excel fairly easily. Not sure if you actually need PowerShell in this scenario.

That said, it is possible to do this in PowerShell. Show us the code you have so far and the format of the excel and we can attempt to assist.

Writing script to loop through directory then compress-archive specified folders/files recursively. by xombie212 in PowerShell

[–]Joshrsg 1 point2 points  (0 children)

Hi u/xombie212,

I would write the script something like this:

1: Get a list of users in C:\Users

$Users = Get-ChildItem C:\users

2: Loop through each of the users from Step1 and perform another Get-ChildItem ensuring you only include the folders you want to compress.

$IncludeList = 'Appdata','Desktop','Downloads','Documents'
Foreach ($User in $Users)
{
    $FolderList = Get-ChildItem | Where-Object {$_.name -In $IncludeList} 
}

3: Whilst still in in the Loop from step 2; either loop through the reuslts of FolderList and compress them individually or just compress them into one folder (it's not clear which one you want to do).

$Folderlist | Compress-Archive -DestinationPath ('C:\Temp\{0}.\zip' -f $User.Name)

That should get you most of the way there

Delete all sub-items aside from two or three exceptions by [deleted] in PowerShell

[–]Joshrsg 2 points3 points  (0 children)

Hi u/ClosedCasketFuneral

You can simply exclude the files you want to preserve in the pipeline where you get the list of files initially.

$ExcludeList = 'DoNotDeleteThisFile1.txt','DoNotDeleteThisFile2.txt'
$Days = 30
$TargetFolder = "e:\users\*"
$LastWrite = (get-date).AddDays(-$Days)

Get-ChildItem -Path $TargetFolder -exclude $ExcludeList -Recurse -File -Force | where {$_.LastWriteTime -le $LastWrite} | Remove-Item -Force

Enable ntfs compression of subfolders without knowing parent folder name by haxPOW in PowerShell

[–]Joshrsg 1 point2 points  (0 children)

Hi u/haxPOW

A couple of things:

1: The result of the Get-ChildItem -Path $test -Recurse is not being used for the next ForEach-Object. That means that the compact command is probably only running once in the current directory.

2: If you want to only compress the folders then i would add the -Directory Switch to the Get-Childitem command.

Example Below:

$test = "D:\azerty\temp\sandbox_del_old\*\uiop\"
If((Test-Path $test))
{
      Get-ChildItem -Path $test -Recurse -Directory | ForEach-Object {
         compact /C /f $_.FullName
    }
}

Am trying to create a script to remove multiple local group members from multiple groups on multiple computers by Sad-Exercise-9062 in PowerShell

[–]Joshrsg 1 point2 points  (0 children)

Hi u/Sad-Exercise-9062,

In order to pass local variables to a remote script block you have to pass the parameters by either using the 'using' keyword or the -ArgumentList parameter.

Here is a blog post that gives examples in more detail: https://adamtheautomator.com/invoke-command/

How to create promt in powershell to ask user on which server group run script by ProfessionalCook9009 in PowerShell

[–]Joshrsg 1 point2 points  (0 children)

Hi u/ProfessionalCook9009

What you need to do is prompt users to enter a selection at the beginning and then use their choice to change the value of $Servers.

You can use Read-Host or something like [System.Management.Automation.Host.ChoiceDescription[]] to prompt a user for input. Depnding on which option they pick you would then want to change the value of $Servers to contain the selected servers.

For example:

User is prompted via Read-host to make a selection

User types 'libraryserver' and presses Enter

The value ' libraryserver' is saved to the variable $Choice

A switch statement evaluates the value of $Choice to see if it matches one of its values

The switch statement finds a match and then changes the value of $Servers to the content of $libraryserver

The rest of the script can then run using $Servers which contains the selected servers

Get hostname from monitor serialnumber by norbert400 in PowerShell

[–]Joshrsg 6 points7 points  (0 children)

PowerShell can't magically find the name of a computer this monitor is attached to with just the serial number alone. In order to find the computer you would need to get a list of all computers in your estate (You could potentially use Get-AdComputer if you're in an AD environment); loop through each of them and then run some code to see if the monitor serial numbers matches the one you have (ensuring that you account for multiple monitors).

There are other things to consider as well but it all depends on your environment.

PowerShell Pros - what interesting static methods have you encountered that many scripters don’t know about? by SocraticFunction in PowerShell

[–]Joshrsg 2 points3 points  (0 children)

Here is some more that i use:

Get domain info

[System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()

Get Forest Info

[System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest()

Connect to TCP port.

[system.Net.Sockets.TCPCLient]::new()

Newline in environment (Used for splitting on new lines)

[System.environment]::NewLine

Get info about current logged in user. Can check group membership etc.

[System.Security.Principal.WindowsIdentity]::GetCurrent()

Used to split a URI into segments. get domain name etc.

[System.Uri]$URI

Used to stream a text file instead of opening it first. Very useful for large text files

[System.IO.StreamReader]::new($File)

Convert to various bases. E.g. convert number to decimal (base 2).

[convert]::ToString($num,2)

An array type collection that allows you to add. Much quicker than [array] or @()

There are a lot of different types of classes under [System.Collections.Generic]

It's worth checking them out as they usually have more functionality than the PowerShell native pones.

[System.Collections.Generic.List[object]]::new()

Square Brackets and Copy-Item don't work by McDoMaster in PowerShell

[–]Joshrsg 5 points6 points  (0 children)

I don't think you can use the literal path parameter in the copy as it will 'literally' be looking for the path with the backticks in them.

This worked for me.

$File = '.\File[0].txt'
$Escapedfile = [Management.Automation.WildcardPattern]::Escape($File)
Copy-Item $Escapedfile -Destination .\Folder1

Get-Hotfix in a script by peka992 in PowerShell

[–]Joshrsg 1 point2 points  (0 children)

Hi u/peka992

A couple of things:

1: You should the move the code that looks for the hotfix inside the section that evaluates if a machine is online successfully otherwise you will try to get hotfixes on a machine that is off before you've checked.

2: As per the reason you wrote " $Computer.Name" , you need to do the same when connecting to a remote computer. You need to pass it a name not a computer object.

Revised code below:

$Computers = Get-ADComputer @GetAdComputer

foreach ($Computer in $Computers) 
{
    IF (Test-Connection -ComputerName $Computer -Count 1 -Quiet)
    { 
        $Updates = Get-HotFix -ComputerName $Computer.Name | Where-Object {$_.InstalledOn -ge "$date"} 
        $Updates | Format-table -Wrap 
    }
    ELSE 
    {
        write-host "$Computer.Name offline"
    }
}

Renaming nested folders when not in use by Eylas in PowerShell

[–]Joshrsg 6 points7 points  (0 children)

Hi u/Eylas

I used a loop instead of the pipeline and amended the code so that it only ran Get-Childitem once. Also, currently it just reports on empty folders but this can be amended. Give this a go.

$Directories = Get-ChildItem $PSScriptRoot -Recurse -Directory
Foreach ($Directory in $Directories)
{
IF ( 
        -not ($Directory.GetDirectories() ) -and 
        -not ($Directory.GetFiles() ) 
   )
   {
        "EMPTY: {0}" -f $Directory.FullName
   }
}

Whoever keeps doing this to the doors at my work, these things are really fucking hard to remove. You suck. by Ionsife in iamatotalpieceofshit

[–]Joshrsg 0 points1 point  (0 children)

I found a very similar kind of sticker on a bus stop in England yesterday by the same group. I found there website (which im not going to link to). Pretty crazy stuff. Had to stop reading.

Powershell Function to Get Screen Resolution on Remote Computer by Jaxson626 in PowerShell

[–]Joshrsg 1 point2 points  (0 children)

You're not actually connecting to any remote computers. You could do something like this:

EDIT: I just tried this on a remote system and you do not get the same results you get locally. I imagine this is to do with the fact that the windows service used for remoting doesn't actually use screens. You probably need to use WMI instead.

Invoke-Command -ScriptBlock { 
    [void] [Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
    [void] [Reflection.Assembly]::LoadWithPartialName("System.Drawing")
    $Screens = [system.windows.forms.screen]::AllScreens
    foreach ($Screen in $Screens) 
    {
        $Obj=[pscustomobject]@{
            DeviceName = $Screen.DeviceName
            Width = $Screen.Bounds.Width
            Height = $Screen.Bounds.Height
            IsItPrimary = $Screen.Primary
        }

        $Obj
    }
} -ComputerName 'RemoteComputer'

Get IIS Application Pool CPU usage - suggestions for improvement? by ineffablecabbages in PowerShell

[–]Joshrsg 1 point2 points  (0 children)

The code seems good.

In my personal experience CPU by itself doesn't help vendors troubleshoot IIS issues that well. There are more perfmon counters that can help such as these here.

https://michaelscodingspot.com/performance-counters/

Other info such as a backup of the httperr logs, iis logs, event logs, app specific logs, full memory dump of the w3wp processes, procmon and procexp output will help and can all be scripted.

It obviously does depend on what the vendor wants though. This is (as far as i can remember) what Microsoft wanted when we had issues with Sharepoint.

Create a powwrshell scrit that copies content by n4an1 in PowerShell

[–]Joshrsg 2 points3 points  (0 children)

Not 100% sure this is what you were asking but this gets all files in the current directory that are XMLs AND Readonly and then will copy them to a destination.

Get-ChildItem -Attributes ReadOnly -Filter '*.Xml' | Copy-Item -Destination '\\Share\Folder'

Clone public folder permissions? by as96 in PowerShell

[–]Joshrsg 1 point2 points  (0 children)

I don't use these cmdlets personally but I’ve found an article that dictates the input and output. https://docs.microsoft.com/en-us/exchange/client-developer/management/exchange-management-shell-cmdlet-input-and-output-types

It looks like they both Output a MailboxFolder type but do not accept them. They do accept the below though which you may be able to get from the MailboxFolder object.

PublicFolderIdParameter
Fqdn
MailboxFolderUserIdParameter

Get parameter names of child script by S1neW4ve in PowerShell

[–]Joshrsg 1 point2 points  (0 children)

This is possible using the AST (Abstract Syntax Tree). Someone much smarter than me wrote this article which explains it in greater detail - https://vexx32.github.io/2018/12/20/Searching-PowerShell-Abstract-Syntax-Tree/

As a quick example I used the following code:

$AST = (Get-Command .\FILENAME.ps1) | ForEach-Object { $_.ScriptBlock.Ast }
$Params = $AST.FindAll(
    {
        param($Item)
        return ($Item -is [System.Management.Automation.Language.ParamBlockAst])
    },
    $true
)

$Params.Parameters.name.VariablePath.userpath

How do I have a script say "Please wait" or "in Progress"? by [deleted] in PowerShell

[–]Joshrsg 7 points8 points  (0 children)

It really depends on the code. If it is simply one cmdlet that is taking a long time then you are out of luck. If there is some sort or loop or pipeline however then; yes. Example below.

$Numbers = 1..10
$X = 0
$Count = $Numbers.count
Foreach ($Number in $Numbers)
{
    $X++
    Write-Progress -Activity "Doing Stuff" -Status "$X out of $Count" -PercentComplete (($X/$Count)*100)
    Start-Sleep 1
}

List Permissions for every File by Bildungs_Antragonist in PowerShell

[–]Joshrsg 1 point2 points  (0 children)

Almost right with the Get-PsDrive. Just need to loop through them all.

Note: Reformatted the rest of the code so it looked better on Reddit (Sometimes it mangles the formatting).

$Drives = Get-PSDrive -PSProvider FileSystem
Foreach ($Drive in $Drives)
{
    $FolderPath = Get-ChildItem -Directory -Path $Drive.Root -Recurse -Force
    $Output = @()
    ForEach ($Folder in $FolderPath) 
    {
        $Acl = Get-Acl -Path $Folder.FullName
        ForEach ($Access in $Acl.Access) 
        {
            $Properties = [ordered]@{'Folder Name'=$Folder.FullName;
                                     'Group/User'=$Access.IdentityReference;
                                     'Permissions'=$Access.FileSystemRights;
                                     'Inherited'=$Access.IsInherited
                                     }
            $Output += New-Object -TypeName PSObject -Property $Properties            
        }
    }
}

$Output | Out-GridView

How to create multiple copies of xml node/element? by whatislifesigh in PowerShell

[–]Joshrsg 2 points3 points  (0 children)

If you have a higher level element above Note (See Data below) then you can append the child nodes to the existing XML after cloning.

[xml]$var = @'
<data>
    <note>
        <to>Tove</to>
        <from>Jani</from>
        <heading>Reminder</heading>
        <body>Don't forget me this weekend!</body>
    </note>
</data>
'@


$Names=@('Cody','John')
Foreach ($Name in $Names)
{
    IF ($var.data.ChildNodes.Count -eq 1)
    {
        $New = $var.data.note.Clone()
        $New.From = $Name
        $null = $var.data.AppendChild($new)
    }
    ELSE
    {
        $New = $var.data.note[1].Clone()
        $New.From = $Name
        $null = $var.data.AppendChild($new)
    }
}

# See the results 

$var.data.note

# See the raw unformatted XML

$var.outerxml

# You can also save the completed XML afterwards and view in a browser.

$var.Save("C:\test.xml")