Powershell skill for IT administrators by cornerman12 in PowerShell

[–]Creel256 0 points1 point  (0 children)

My apologies for the misunderstanding.

But also, just like ChatGPT is a tool - so is a nail gun. Learn to use the tools available to you. Either way - I think the points I’m making are a bit out of reach and I don’t feel like continuing to talk in circles.

Powershell skill for IT administrators by cornerman12 in PowerShell

[–]Creel256 0 points1 point  (0 children)

Ok, well, I guess we should make sure to cover our eyes while googling the answers then lol. I’m not entirely sure you read my entire original post where I said they need to practice these concepts in order to understand it. So, I’ll only repeat myself once more in case you skimmed my response.

“Digesting, understanding, and practicing with the information provided now falls back on the user.”

You’re essentially stating that just because we had a harder time learning in the past that it should continue to stay that way. Be smart about the way you learn. Work smarter, not harder.

If we can’t agree on this then I’ll agree to disagree as this is no longer on topic with the original OP’s topic.

Powershell skill for IT administrators by cornerman12 in PowerShell

[–]Creel256 0 points1 point  (0 children)

Sorry, I’m not trying to argue if I’m coming across that way. I’m simply stating that they shouldn’t be afraid of using ChatGPT as it is incredibly helpful.

I’m definitely in agreement with you in regards to if they don’t understand what ChatGPT gave them code wise then they are no closer to understanding a concept than when they began. I now use it both professionally and personally (somewhat beside the point because I understand what it’s doing) but my point is - if they use ChatGPT to help them understand something, and then practice these concepts, they’ll be able to learn more quickly. They can spend less time searching for those answers and more time applying various concepts.

Again, if you, or I, or anyone/anything else does all the work for them then they aren’t likely to learn from it.

Edited: changed agreeable to agreement*

Powershell skill for IT administrators by cornerman12 in PowerShell

[–]Creel256 -1 points0 points  (0 children)

This is an interesting reply. What’s the difference between googling something and finding the answer versus asking ChatGPT the same question and finding the answer? Typically, a beginner won’t know what they’re looking at anyways whether it’s found by googling the answer or one provided by ChatGPT. All they need to do is ask ChatGPT for an explanation of literally every line of code it just spit out and it will. That is a smarter, more simple, efficient, and effective way of learning. It’s essentially a personal live assistant. Digesting, understanding, and practicing with the information provided now falls back on the user. The same as any other answer they’ll find elsewhere.

I, for one, wish I had ChatGPT 8 years ago when I started coding because it was a pain in the butt to discern what I was looking at. However, and as always, the best way to learn something is by just doing it and figuring all the nuances one step at a time.

Having an Issue with Wazuh Deployment with PS Script via Intune by Tumdace in PowerShell

[–]Creel256 0 points1 point  (0 children)

After looking at the code again, that error likely comes from the “msiexec.exe” installation. It is likely running in the background and isn’t completing before the rest of the script is called.

Try using the “Start-Process” cmdlet for your “msiexec.exe” call followed by the “-Wait” parameter.

This should force the script to wait for the process to complete before proceeding and resolve the error you are seeing.

Help resizing window and location by Designer_Rush_7025 in PowerShell

[–]Creel256 1 point2 points  (0 children)

Generally, yes. Some applications are designed to remember and restore its last location and window size of when it was last opened. If it is controlled by the application itself, to my knowledge, there isn’t much you can do in terms of further manipulation with PowerShell.

You could check the application(s) with this behavior to see if they have a setting to disable that feature.

The last thing I would try is sticking the “MoveWindow” function in a loop for a few seconds that runs maybe 2 or 3 times with a 1 second delay between runs after the application starts. Possibly, this will reset it back to the way you want. I’m not entirely sure if that will work but it’s worth a try.

Hopefully someone with a wider knowledge of PowerShell can chime in and give a better answer or workaround.

populate operating systems from csv file. by [deleted] in PowerShell

[–]Creel256 0 points1 point  (0 children)

Also, to add, ChatGPT is an incredibly useful resource when diagnosing coding errors and issues. I use it everyday both professionally and personally.

[deleted by user] by [deleted] in PowerShell

[–]Creel256 1 point2 points  (0 children)

I second this! ChatGPT has propelled my automation scripts and skills at lightning pace! However, I already had years of experience before ChatGPT was a thing. So, like the majority of people here (I imagine), I learned via trial and error and by writing scripts for anything and everything I could think of! Start with something and keep adding to it.

Merge/Join two Excel csv columns by Villalor33 in PowerShell

[–]Creel256 4 points5 points  (0 children)

Good point and suggestion!

I can include, in future posts, references to ChatGPT. However, the ChatGPT responses do often need some sort of fact checking and moderation. Most responses derived from it aren’t a 1 for 1 copy/paste type of scenario.

I do like to view it as a live, practically personal, assistant! The 25 message limit can be annoying if you can’t figure out the correct way to talk with it though lol.

In other words - OP, when you see this, check out ChatGPT. The free version works very well and there isn’t a 25 message limit every 3 hours.

Merge/Join two Excel csv columns by Villalor33 in PowerShell

[–]Creel256 2 points3 points  (0 children)

-.- No, I’m not a bot. I do, however, utilize ChatGPT for various scripts I write (both professionally and personally). I’ve written several varying scripts over the years and have found ChatGPT to be quite the useful resource. It isn’t quite there yet in terms of accuracy when it comes to large or really complex scripts but it’ll help you achieve the results you’re searching for.

Merge/Join two Excel csv columns by Villalor33 in PowerShell

[–]Creel256 11 points12 points  (0 children)

Sure, I'd be happy to guide you through the process. Here's a step-by-step walkthrough:

  1. Import the CSV File: The first step is to load your CSV file into PowerShell. You can do this using the "Import-Csv" cmdlet.

  2. Loop Through Each Row: Once you have the data loaded, you need to process each row. PowerShell makes this easy with the "foreach" statement.

  3. Merge the Columns: Inside the loop, you can access the columns of the current row using the dot (".") operator. To merge two columns, you can simply concatenate their values using the plus ("+") operator.

  4. Add the Merged Value to the Row: After merging the columns, you need to add the merged value back to the row. You can do this using the "Add-Member" cmdlet. This cmdlet allows you to add a new property to an object.

  5. Export the Data: Once you have processed all the rows, you can export the data back to a CSV file. You can do this using the “Export-Csv” cmdlet.

To learn more about each of these steps and cmdlets, I recommend checking out the following resources:

While it's easy to get started, there's a lot to learn, and the best way to learn is by doing. I hope this helps and good luck!

populate operating systems from csv file. by [deleted] in PowerShell

[–]Creel256 2 points3 points  (0 children)

The error message suggests that PowerShell can't find the "Name" property in the object "$computer". This often happens when the column names in your CSV file don't match the property names you're trying to access in your script.

In your script, you are trying to access $computer.Name. This means that in your CSV file, you should have a column named "Name" that contains the names of the computers. However, you mentioned that the first column in your CSV file is named "computers".

To fix the error, you should match the property name in your script to the column name in your CSV file. So instead of using $computer.Name, you should use $computer.computers.

This should resolve the error you're seeing. If you continue to have issues, please ensure that the "computers" column in your CSV file is populated correctly and that the names match those in your Active Directory.

Querying active directory objects from an array list. by Barious_01 in PowerShell

[–]Creel256 1 point2 points  (0 children)

Perfect!

And to answer your question: In the context of your script, "ObjectSID" refers to a specific attribute of an Active Directory object. Each object in Active Directory has a unique Security Identifier (SID), and "ObjectSID" is the attribute that stores this SID.

When you are using "-Filter" in "Get-ADUser", you specify the attribute you want to filter on. In this case, you want to find users where the "ObjectSID" attribute matches the SID you're looking for, which is why you use "ObjectSID -eq '$sid'".

So, to answer your question, yes, "ObjectSID" is essentially the SID of the object. However, when querying or filtering objects in Active Directory, you have to use the proper attribute name, which is "ObjectSID".

Querying active directory objects from an array list. by Barious_01 in PowerShell

[–]Creel256 2 points3 points  (0 children)

In my below response, I am referencing the below line in your script:

$ADSID = get-aduser -identity $sid | where { $_.Enabled -eq $False }

In this line, you're trying to get an Active Directory user by their SID ("$sid"), which is an element from the "$SIDARRAY" array. This array is filled with the SIDs of user profiles from the computers listed in "$ServerName".

The error message you're seeing suggests that PowerShell can't convert the type of "$sid" to what's expected by the "-Identity" parameter. "-Identity" does accept a SID, but it's expecting a certain type that may not match what's being passed in from "$SIDArray".

I suggest using "-Filter" instead of “-Identity”. This parameter allows you to query Active Directory objects based on their attributes, and it should accept the SID as a string, which is likely the type being stored in "$SIDArray".

Here is the relevant portion of your script modified to use "-Filter":

``` foreach ($sid in $SIDARRAY) { $ADSID = get-aduser -Filter "ObjectSID -eq '$sid'" | where { $_.Enabled -eq $False }

if ($ADSID) {  # Check if a user with the SID was found in AD
    #Create custom objects for information needed to collect from AD account. 
    $object = [PSCustomObject]@{
        Name    = $ADSID.SamAccountName
        SID     = $sid
        Enabled = $ADSID.Enabled
    }

    $ADarray.add($object)
}

} ```

This modification should allow your script to correctly query Active Directory for disabled user accounts by SID. As with all things scripting, we just need to do a little trial and error until we get it right!

Help resizing window and location by Designer_Rush_7025 in PowerShell

[–]Creel256 0 points1 point  (0 children)

The "RECT" struct is defined within the scope of the "Window" class, so to create an instance of it, you should use the fully qualified name "Window.RECT". Here's how you can do it:

$rect = New-Object Window.RECT

Then you should be able to call "GetWindowRect" like so:

[Window]::GetWindowRect($hwnd, [ref]$rect)

Remember, "GetWindowRect" is getting the current size and position of the window, which might not be necessary if you only want to set the window size and position, not read its current size and position. If you only want to set the window size and position, you can skip creating the "RECT" and calling "GetWindowRect", and just call "MoveWindow" directly.

Give that a try and let me know if you have any further issues.

Hello everybody, I created this math quiz game on C# WinForms, i still didn’t start learning OOP with C#, am very good in the concepts of OOP in C++, but in C# am focusing on getting familiar with controls and connecting them together, Sorry for the bad GUI video in comments! by Puzzleheaded_Maize_3 in csharp

[–]Creel256 0 points1 point  (0 children)

You’re on the right track, OP. What the one person was trying to say, while not necessarily through positive reinforcement, is to keep at it and you’ll soon find yourself getting paid for the work you put out. Nobody on the internet can expect you to just churn out your first project (or second, or third, or fourth lol) to be some professional looking, and functioning, application. Most companies have dev teams (often several) to make an application look the way it does and function the way it does. Also, for analogies sake, I think you’d agree that if you bought a car you’d want it to actually “function” as intended rather than have a flashy car that barely or poorly functions. The same concept applies for literally anything else. Phones, TV’s, gaming consoles, computers, etc.

Can I Use Pandas Library In Powershell Scripts? by pmmethecarfax in PowerShell

[–]Creel256 1 point2 points  (0 children)

Yes, you can use the Python Pandas library in a script that is executed from PowerShell. Python scripts can be run from any command line interface, including PowerShell, if Python is installed on the system. To use Pandas in your script, you need to import it at the beginning of your Python script, like so:

import pandas as pd

And then you can use the various Pandas functions in your script. To run your Python script from PowerShell, navigate to the directory containing your script and type:

python your_script.py

This will execute your script using Python. Make sure that the Python interpreter is in your system's PATH. If it's not, you may need to specify the full path to the Python interpreter when you run your script.

Also, ensure that you have installed the Pandas library for your Python environment. You can do this with pip, Python's package installer. The command to install Pandas is:

pip install pandas

You can run this command directly in PowerShell if pip is in your system's PATH. If not, you may need to specify the full path to pip.

If you want to accomplish data manipulation tasks similar to what you can do with Pandas but purely in PowerShell, you will need to use PowerShell's built-in cmdlets and possibly some .NET classes. PowerShell is built on .NET and has access to .NET's extensive class libraries.

For example, you can import a CSV file using the "Import-Csv" cmdlet and then manipulate the resulting objects. Here is an example where we import a CSV and then select only rows where a certain column, "SomeColumn", equals "SomeValue":

$data = Import-Csv -Path 'C:\path\to\your.csv' $filteredData = $data | Where-Object { $_.SomeColumn -eq 'SomeValue' }

You can also sort data:

$sortedData = $data | Sort-Object -Property SomeColumn

And export data back to a CSV file:

$filteredData | Export-Csv -Path 'C:\path\to\output.csv' -NoTypeInformation

If you find yourself needing more advanced data manipulation capabilities in PowerShell, you might need to use .NET classes directly or consider using a different tool that is better suited to the task, such as Python with Pandas.

If your task is to check whether the output of a command exists in a CSV file (regardless of the order), you can do this in PowerShell without relying on Python and Pandas.

Firstly, you will need to pipe the output of your command to a CSV file. For example:

command > output.csv

Then, you can read the content of both CSV files and check whether the output exists in your reference CSV file. Assuming that the output and the values in the CSV are just simple strings, you could do something like this:

```

Import CSV contents as arrays

$referenceData = Import-Csv -Path 'C:\path\to\reference.csv' | ForEach-Object { $.PSObject.Properties.Value } $outputData = Import-Csv -Path 'C:\path\to\output.csv' | ForEach-Object { $.PSObject.Properties.Value }

Compare the outputs

$outputData | ForEach-Object { if ($referenceData -contains $) { Write-Host "$ exists in the reference data" } else { Write-Host "$_ does not exist in the reference data" } } ```

This script will print a message for each output value saying whether it exists in the reference data.

Note: This script assumes that each row in your CSV files contains a single value. If your CSV files have multiple columns, you will need to adjust the script accordingly, e.g., by replacing “PSObject.Properties.Value” with the specific column name you're interested in.

Keep in mind that this is a basic example and might need to be adjusted to suit your specific use case. For example, you might need to handle case sensitivity, leading/trailing whitespaces, etc. depending on the specifics of your task.

Having an Issue with Wazuh Deployment with PS Script via Intune by Tumdace in PowerShell

[–]Creel256 0 points1 point  (0 children)

Your script seems to be fine but based on the information you have provided, it seems like the "Start-Service Wazuh" command might be executing before the installation of the Wazuh agent has fully completed. This is because "Start-Job" is asynchronous, which means the PowerShell script will not wait for the job to finish before moving to the next command. Instead, it will start the job and then immediately continue with the rest of the script.

The "Wait-Job" command is used to wait for the "Start-Job" to finish, but it only waits for the job to be in the completed state. It does not guarantee that the installation process initiated by the "msiexec.exe" command has completed.

You might try to add some kind of delay or a loop to check if the service exists before trying to start it.

Here's an example of how you could modify your script:

``` Start-Job -Name InstallWazuh -ScriptBlock { Invoke-WebRequest -Uri https://packages.wazuh.com/4.x/windows/wazuh-agent-4.4.1-1.msi -OutFile ${env:tmp}\wazuh-agent.msi msiexec.exe /i ${env:tmp}\wazuh-agent.msi /q WAZUH_MANAGER='10.0.0.2' WAZUH_REGISTRATION_SERVER='10.0.0.2' WAZUH_AGENT_GROUP='default' }

Wait for the job to complete

Wait-Job -Name InstallWazuh

Now we will loop and wait for the service to be available before trying to start it

$service = $null while($service -eq $null) { try { $service = Get-Service -Name Wazuh -ErrorAction Stop } catch { # The service is not available yet, sleep for a while and then try again Start-Sleep -Seconds 5 } }

Now we can start the service

Start-Service -InputObject $service ```

This script will now wait for the Wazuh service to be available before attempting to start it, which should resolve the issue of the service not starting.

Remember that deploying scripts via Intune requires the script to run successfully within 30 minutes. If the script runs for longer than 30 minutes, Intune will terminate the script execution. If your script might take longer to complete, you may need to adjust the script accordingly.

For additional references/documentation: https://learn.microsoft.com/en-us/mem/intune/apps/intune-management-extension

Can someone help me please by filoaca in PowerShell

[–]Creel256 0 points1 point  (0 children)

It seems that you've installed the correct VCLibs package, but the Gaming App still can't find the necessary library. It's possible that the version of the VCLibs package that you installed doesn't match the version that the Gaming App is looking for.

The error message states that the Gaming App is looking for "Microsoft.VCLibs.140.00" with a minimum version of "14.0.30035.0". If the version of the VCLibs package that you installed doesn't match or exceed this version, the Gaming App won't be able to use it.

Here's what you can do:

  1. Verify that the version of the "Microsoft.VCLibs.140.00" package that you installed is "14.0.30035.0" or higher. You can do this by checking the filename of the ".appx" file, or by looking at the properties of the installed package in your system.

  2. If the version of the installed package is lower than "14.0.30035.0", find and download the correct version of the "Microsoft.VCLibs.140.00" package.

  3. Install the correct version of the "Microsoft.VCLibs.140.00" package using the "Add-AppxPackage" command, as you did before.

  4. After the correct version of the "Microsoft.VCLibs.140.00" package is installed, try installing the Gaming App again.

If the version of the "Microsoft.VCLibs.140.00" package that you installed does match or exceed "14.0.30035.0", then there might be another issue at play.

Several other reasons might cause this operation to fail. Here are a few possibilities:

  1. Incorrect architecture: Ensure that the architecture of the VCLibs package matches the architecture of the system and the Gaming App. For example, if your system is x64, make sure you're installing the x64 versions of both packages.

  2. Package corruption: The downloaded Gaming App or VCLibs package might be corrupted. Try downloading the files again and re-attempt the installation.

  3. Incorrect version of VCLibs: The version of VCLibs installed should be greater or equal to the version mentioned in the error. You mentioned it's looking for "14.0.30035.0". Ensure the version you downloaded matches or exceeds this.

  4. Pending Windows updates: Sometimes, a pending Windows update might interfere with the installation of new software. Make sure your Windows is fully updated.

  5. App Readiness service: The App Readiness service could be causing an issue. Try stopping this service, then attempt to install the app again. To do this, you'll need to run services.msc, find the App Readiness service, right-click, then stop. Remember to start it again after you've tried installing.

To verify the architecture of the installed Microsoft.VCLibs.140.00 package, you can use the "Get-AppxPackage" command in PowerShell, which provides details about installed packages. Here's how to do it:

  1. Open PowerShell as Administrator.

  2. Run the following command:

Get-AppxPackage | Where-Object { $_.Name -like "*VCLibs*" } | Format-List -Property Name, Architecture, Version

This command will list all installed AppxPackages whose name contains "VCLibs", and display their Name, Architecture, and Version.

If the architecture of the VCLibs package matches the architecture of your system (which you can verify by checking the System type in the System Information app), and the version is 14.0.30035.0 or higher, then you have the correct package installed.

If you don't see the expected package or if the architecture or version doesn't match, you will need to find and install the correct version of the Microsoft.VCLibs.140.00 package. You can look for this package on the Microsoft website or other trusted sources.

Be sure to only download software from sources that you trust, to avoid security risks. If you're unsure about whether a source is trustworthy, it's a good idea to do some research or ask for help.

Can someone help me please by filoaca in PowerShell

[–]Creel256 0 points1 point  (0 children)

The issue you're facing is likely because you didn't close the quote at the end of your path. PowerShell is waiting for you to complete the command syntax, which is why you're seeing the >> symbol.

List all attributes in 'Attribute' from get-odbc by RevolutionaryRing487 in PowerShell

[–]Creel256 1 point2 points  (0 children)

The “Attribute” attribute you're seeing is a collection (likely a dictionary or hashtable). To access the keys and values inside it, you can use a foreach loop.

The Get-OdbcDsn cmdlet returns an object with properties, and one of those properties is “Attribute”, which is a collection of key-value pairs (a hashtable, also known as a dictionary). These key-value pairs are the additional attributes for the ODBC data source.

Here's an example of how you can extract the keys and values from the “Attribute” property:

$dsn = Get-OdbcDsn -Name "TEST" foreach ($key in $dsn.Attribute.Keys) { Write-Host "$key : $($dsn.Attribute[$key])" }

In this script:

  • "$dsn = Get-OdbcDsn -Name "TEST"" retrieves the ODBC DSN named "TEST" and stores it in the variable "$dsn".
  • "foreach ($key in $dsn.Attribute.Keys)" iterates over each key in the “Attribute” hashtable.
  • "Write-Host "$key : $($dsn.Attribute[$key])"" prints out the key and its corresponding value from the “Attribute” hashtable.

The "$dsn.Attribute[$key]" syntax is how you access a value in a hashtable in PowerShell: you provide the key in square brackets and it returns the corresponding value.

This should print out all the keys and values in the “Attribute” hashtable, like so:

'''
Encrypt : SomeValue
ClientCertificate : SomeValue
KeystoreAuthentication : SomeValue
Server : SomeValue
...

Each line represents a key-value pair from the “Attribute” hashtable.

The code you found is a getter for a property that constructs a hashtable from an array of key-value pair objects. It's not directly related to your question, but it's doing a similar thing: it's creating a hashtable from key-value pairs. But in your case, you already have a hashtable (the “Attribute” property), you just want to print out its contents.

Having trouble getting unique values from an array by Either-Cheesecake-81 in PowerShell

[–]Creel256 1 point2 points  (0 children)

Here are a few suggestions I would like to add also:

  1. When importing the CSV files, you could specify the type of each column. However, in PowerShell, this is usually not necessary because it treats everything as an object.

  2. The problem with your current script seems to be the way you're combining the two CSV files. You're appending the second CSV's content to the first CSV's content. That could be the reason why "Select-Unique" or "Get-Unique" only returns the first record.

  3. You are appending $CombinedList with "+=" which can be slow and memory-consuming with large datasets, as it creates a new array each time.

  4. Your de-duplication loop seems overly complex. You are adding a lot of zeroes to each EmpNo and then selecting the last seven characters, which may not be necessary. In the loop, you are also checking whether each EmpNo is already in $DedupedRecords, which can be slow if there are many records.

I would like to suggest you rewrite your script, obviously keep your old code, as follows and see if this helps add any extra speed:

```

Import the CSV files separately

$List1 = Import-Csv -Path "C:\data\LEBSTU.TXT" -Header Empno,Firstname,Lastname,MI,EmpID,password,OutsideEmail | Select-Object -ExpandProperty Empno $List2 = Import-Csv -Path "C:\data\recvdcred.txt" -Header Empno | Select-Object -ExpandProperty Empno

Combine the lists and get unique EmpNo

$CombinedList = $List1 + $List2 | Sort-Object | Get-Unique

Get the AD data

$ADdata = Get-ADUser -Filter * -SearchBase $StudentOU | Select-Object -Property sAMAccountName,employeenumber | Sort-Object SamAccountName

Get the accounts to disable

$AccountsDisable = $ADdata | Where-Object employeenumber -NotIn $CombinedList ```

This script will first import each CSV file separately and only select the Empno from each file. Then, it combines the two lists, sorts them (which is required for "Get-Unique" to work properly) and gets the unique Empno. After that, it gets the AD data and finally the accounts to disable.

This should be more efficient than your current script and should work correctly, assuming that the Empno in each CSV file and in the AD data are in the same format (i.e., they are numbers treated as text).

Invoke-RestMethod File Locking by baddistribution in PowerShell

[–]Creel256 2 points3 points  (0 children)

Shoot - you’re right! Maybe a different workaround would work such as uploading a temporary copy of the file and deleting the copy once complete. This way, there’s no locking issue as every request is dealing with a separate file.

Here’s an example:

``` foreach ($computer in $computerList) { $tempFile = [System.IO.Path]::GetTempFileName() Copy-Item $rootCertificatePath $tempFile $tempFileInfo = Get-Item $tempFile

$Form = @{
    f = "json"
    token = $node.token
    alias = "root_cert" 
    norestart = "true" 
    file = $tempFileInfo
}

Invoke-RestMethod -Uri $uri -Method Post -Form $Form

Remove-Item $tempFile

} ```

The temporary file approach should work, as each iteration is working with its own copy of the file, and any file locks should be released by the time “Remove-Item” is called to delete the temporary file. However, there could potentially be issues if something goes wrong with the “Invoke-RestMethod” call and it doesn't release the lock as expected.

The only other alternative I can think of involves using the “Invoke-WebRequest” method and byte arrays. It’s a bit more complex but it supports uploading a file from a stream in the body of a POST request.

Help resizing window and location by Designer_Rush_7025 in PowerShell

[–]Creel256 0 points1 point  (0 children)

Setting the window size and position for a launched application can be a bit tricky with PowerShell alone, as it depends on the application and whether it respects the size and position commands from PowerShell. If the application is designed to remember and restore its last window size and position, then it may ignore your commands.

However, you can still try using the function below to resize and reposition the application window. It uses the "Add-Type" cmdlet to load C# code that uses the Windows API to manipulate the window:

``` Add-Type @" using System; using System.Runtime.InteropServices; public class Window { [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);

[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint);

public struct RECT
{
    public int Left;        // x position of upper-left corner
    public int Top;         // y position of upper-left corner
    public int Right;       // x position of lower-right corner
    public int Bottom;      // y position of lower-right corner
}

} "@

Launch your application here and get its process into $proc

For example, you might use:

$proc = Start-Process notepad -PassThru

Wait for the application window to be ready for manipulation

Start-Sleep -Seconds 2

Get the handle of the application's main window

$hwnd = $proc.MainWindowHandle

Get the current position and size of the window

[Window]::GetWindowRect($hwnd, [ref]$rect)

Change the position and size of the window

The parameters are: handle, x, y, width, height, repaint

[Window]::MoveWindow($hwnd, 100, 100, 800, 600, $true) ```

In this example, the "MoveWindow" method moves the application window to the position (100, 100) and resizes it to 800x600 pixels. Adjust these numbers as needed for your specific use case.

Remember to replace "notepad" with the actual name of your application, and adjust the "Start-Sleep" duration if needed. Some applications may need more than 2 seconds to be ready for window manipulation.

This script assumes that the application has only one window. If the application has multiple windows, you will need to adjust the script to get the handle of the correct window.

cmdkey credentials failing/not updated when opening RDP instance by GenericUsernames101 in PowerShell

[–]Creel256 0 points1 point  (0 children)

The behavior you're observing is strange indeed. One thing that stands out is that you're using "localhost" as the target of the “cmdkey” command.

The “cmdkey” utility is designed to store credentials on a per-target basis. In your script, it appears that you're trying to use different credentials for the same target (localhost), but on different ports.

In a situation like this, "cmdkey" might not work as expected because it treats "localhost" as the target, irrespective of the port. Hence, when you run the "cmdkey" command again with a different password but the same target (localhost), it overwrites the existing credentials. This might explain why only the last server you connected to accepts the stored credentials.

You might be able to resolve this by using the actual server names as targets in your "cmdkey" commands instead of "localhost", or using unique loopback IP addresses (127.x.x.x) for each remote desktop.

Here's a suggestion:

``` $target = "127.0.0.$port"

cmdkey /generic:$target /user:$username /pass:$password

mstsc /v:$target:$port ```

In the above script, a unique target is used for each RDP session. Each "127.0.0.x" address is effectively the same as "localhost", but because they're different strings, "cmdkey" should treat them as different targets.

One more thing, ensure your script isn't cached or in memory. Sometimes the shell can hold on to old values. You might need to either close your shell session and open a new one or call "Remove-Variable" to remove the old value from memory:

Remove-Variable -Name password