Quantcast
Channel: PowerShell General
Viewing all 10624 articles
Browse latest View live

Downloading (Exporting) Information form Vendor Web Consoles

$
0
0

I am having really difficult time doing this and hoping that someone already did something similar and can get me through this "wall" in front of me.

I have various consoles that I am working with and my goal is to schedule a task that  Exports reports from these vendors and send them in an email or save them to the drive.

The vendor web consoles I am working with are Trend Micro and Bit9.

In both cases, I am not able to authenticate using invoke-webrequest (unless I am authenticated and just can't tell)

The only way so far, was to use InternetExplorer.Application. This way, I am able to navigate all the way to the "Export" button, but it pulls up a dialog to Save/Save As and requires manual intervention and IE must be visible (this defeats my scheduled task requirement)

Below is my code for IE: 

 

My code using Invoke-WebRequest 

 


Gathering information about computer name and network card information

$
0
0

Dear Powershell users,

I'm trying to make a Powershell that does the following:
1. Load the computers.txt, inside this *.txt file there are computers listed
2  Gives the computername
3. Gives the network card information about devicename, driverversion, driverdate
4. Writes each computer listed in computers.txt on a new line
5. Save this in a *.csv file 

$computerlist = Get-Content -Path "C:\temp\computers.txt"
$computername = Get-WmiObject Win32_ComputerSystem -cn $computerlist | Select-Object Name
$networkcard = Get-WmiObject Win32_PnPSignedDriver -cn $computerlist | select driverdate, devicename, driverversion | where {$_.devicename -like "*Network Connection*"}

$Object = New-Object PSObject -Property @{
Computername = $computername.Name
Devicename = $networkcard.devicename
Driverdate = $networkcard.DriverDate
Driverversion = $networkcard.driverversion
}
Sort-Object Computername, Devicename, Driverdate, Driverversion
Write-Output $Object | Export-Csv c:\temp\test1232.txt


In my thoughts the output most looks like this
Computername1 - driverdate - devicename -  driverversion
Computername2 - driverdate - devicename -  driverversion
Computername3 - driverdate - devicename -  driverversion
 
Now I have managed to gather some information on the internet, but I don't yet have the knowledge the write my own powershell scripts. Is there anyone who can show me the right direction?

Kind regards,
Martijn 

 

Local Admin Report with Multiple Creds to loop through-possible?

$
0
0

Howdy

I was able to get this script working from some posts on here. I need to find out if anyone can help me add in some code that would try different credentials if the creds that I was logged in with failed. There are standalone servers and multiple domains. I found one post on another site with a script that had multiple creds specified and you get prompted to enter them. The problem is that if you provide 2 or 3 sets of creds, all of them have to work against each server or an error keeps coming up. 

Can anyone help with a way to have it loop through a few different creds, and I'd like to somehow encrypt the password in the script for the creds so I can schedule it to run as a task and then get it emailed out. 

I put a couple comments in bold as I am not sure I need the lines below them? 

$admins = @()

foreach ($computername in get-content Q:\Scripts\Powershell\Test\Systems.txt){

write-host $computername

$localGroupName = "Administrators"

$group = [ADSI]("WinNT://$computerName/$localGroupName,group")

$group.Members() |

    foreach {

        $AdsPath = $_.GetType().InvokeMember('Adspath', 'GetProperty', $null, $_, $null)

        $a = $AdsPath.split('/',[StringSplitOptions]::RemoveEmptyEntries)

        $name = $a[-1]

        $domain = $a[-2]

        # Ignore non-local accounts

        if ($domain -eq $computerName)

        {

  $user=([ADSI]"WinNT://$($computername)/$($name)")

            $adminInfo = @{

                Name = $name;

                Computer = $computerName;

                LastLogin = $(([ADSI]"WinNT://$($computername)/$($name)").lastlogin)

                NeverExpires=[bool]($neverexpiresflag -band $user.userflags[0])

                Disabled=[bool]($disabledflag -band $user.userflags[0])

            }

            $admin = New-Object -TypeName PSObject -Property $adminInfo

            $admins += $admin

        }

    }

}

#I didn't think this line was needed either?

$date=(get-date -format yyyyMMddHHmm)

# What does this line actually do? I got confused when I tried to remove it, but I'm not pulling domain accounts?

$outpath=$srcdomain +"_Admins_"+$date+".csv"

$admins | select name,computer,lastlogin,neverexpires,disabled | Export-Csv -NoTypeInformation Q:\Scripts\Powershell\Test

Triggerring a script with parameters from another script

$
0
0

I've got a simple yet lengthy script that does some server checks for me. The script will take a hostname or a list from a txt file (using $args). When run it chacks $args and then asks for a username and password. I'd need that script to run on schedule but not sure how to pass the username and password into it.

Compare folders and check if file exists anywhere

$
0
0

I need to compare many folders, which contain many files (millions) which are nested inside long file paths (> 260 char.)

The input file contains a source and a destination folder. the script should check if the files in the source folder exist anywhere inside the destination folder.

 

So it shouldn't check I the file exists in the same folder on the destination folder (as the script below does) but anywhere in the destination folder structure.

 

All files which do exist on the source and not in the destination should be exported to csv.

 

any suggestion ?

$folders = Import-CSV '.\compare-folders.csv'

foreach ($folder in $folders)
    {
    $source = Get-ChildItem -Recurse -path $folder.source
    $destination = Get-ChildItem -Recurse -path $folder.destination
    Compare-Object -ReferenceObject $source -DifferenceObject $destination
    }

 

Looking for an Open Source Enterprise Job Scheduler that Executes PowerShell Scripts

$
0
0

I'm looking for an Open Source Enterprise Job Scheduler that executes PowerShell scripts. However, I haven't found anything useful with Google.

I'm looking for something like UC4, AutoSys, CA7, etc. that is not Java based. PowerShell works fine with Scheduled Tasks until I need a job dependency based on a remote machine. I also need a way to launch remote jobs. Although Unix is in our shop, I do not currently have the need for Unix job dependencies.

Can anyone point me to any leads?

Thanks.

Powershell WPF (XAML) GUI: Hide WPF button on second WPF GUI - on load of second GUI

$
0
0

All,

Thanks for viewing this post. I'll try to be as clear as I can in describing what I have and am trying to do.

I have a WPF GUI built in Visual Studio, XAML Code. I added this code to Powershell. I have 2 buttons on the form - powershell coded - doing 2 separate tasks however each button calls a second WPF GUI form.

The second form - also XAML code - displays a textbox and 2 buttons. Each button on form 2 performs the two separate tasks.

I would like to hide the buttons depending on which button on form 1 is selected.

 

For example: MainForm and Display_User_ID_Form

MainForm

Button 1: Rebuild_User_Profile

Button 2: Add_ID_RD_Group


Display_User_ID_Form

Textbox (for user ID)

Button 1: Rebuild_User_Profile

Button 2: Add_ID_RD_Group

 

If MainForm.Rebuild_User_Profile is pressed 2 things should happen, 1) Display_User_ID_Form loads and 2) Hide Display_User_ID_Form.Add_ID_RD_Group button

 

If MainForm.Add_ID_RD_Group is pressed 2 things should happen, 1) Display_User_ID_Form loads and 2) Hide Display_User_ID_Form.Rebuild_User_Profile button

 

If you have any questions please let me know.

 

Thanks!

Looking for remote execution ideas outside of WinRM

$
0
0

The company I am currently working with has WinRM disabled across the board and turning it on is not an option.

I have been performing  all of my remote task so far using WMI, Built in  (not WinRM) cmdlets and with a lot of psexec.

Currently I've run into an issue with psexec where I am trying to execute a ps1 file on the remote computer and even though it runs, it gives me an error from within the code that does not happen when I run it locally from any machine.

simply, I wrote a perfectly working cmdlet to open and excel file and save the required tab as a csv for import into scripts. And I need to get this to execute correctly on a remote machine "the one that has EXCEL installed"

I would really appreciated any alternative cmdlet, .net class, or comObject, etc. that anyone can recommend to accomplish this without WinRM.

Thank you!!!

 

 

 

 

 

 

 


add-printdriver

$
0
0

I am running PowerShell v5.0.10105.0.   I need to use the cmdlet Add-PrinterDriver yet it is not supported.   Get-Command does not display this cmdlet.

I've googled looking for the .PSD1 module but have not found it.   How do I download and use this module?   And, based on its name, how come it is not part of PowerShell?  It seems like this should be a standard command included with PowerShell when it gets installed.

thanks.   

Redirect Results of Powershell Script to a Text File

$
0
0

The powershell script below displays the application programs installed on each computer. It displays the UninstallString and the name of each application installed. I would like to redirect the results to a text file. I am having difficult time getting the script to redirect the results to a text file.

$Computers = Get-Content .\computers\computers.txt

              $RegistryPath = 'SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\',

                            'SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\'

           foreach ($Computer in $Computers) {

            $Registry = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey([Microsoft.Win32.RegistryHive]::LocalMachine,$Computer)

            foreach ($RegPath in $RegistryPath) {

                ($Registry.OpenSubKey($RegPath)) | foreach {

                    $_.GetSubKeyNames() | ForEach-Object {

                        $ApplicationName = ($Registry.OpenSubKey("$RegPath$_")).GetValue('DisplayName')

                        $UninstallString = ($Registry.OpenSubKey("$RegPath$_")).GetValue('UninstallString')

                        if ([bool]$ApplicationName) {

                            New-Object -TypeName PSCustomObject -Property @{

                                'ComputerName' = $Computer

                                'UninstallString' = $UninstallString

                                'Application' = $ApplicationName

                              

                            }

                         }

                      }

                   }

                }

             }

 

Runing GUI from PS prompt results bad image quality

$
0
0

Good evening,

When I run my GUI from Powrshell ISE, all buttons are curved and beatifull, but when I run my gui from prompt or I right click on the file and I choose "Run with Powershell", all GUI elements are flat and looks like windows 95 buttons.

Do you know why is that?

 

Thank you

add-printer

$
0
0

on a 2012 server I can run add-printer commands.

add-printer -ConnectionName \\OurPrintServer\FNPAS10Q   this works and it adds the printer to my 2012 server.

if you run add-printer -comp it will Auto-Fill the rest of your command to -ComputerName.  Yet I can't get this to work. 

Add-Printer -ComputerName '\\PCname1'  -ConnectionName \\OurPrintServer\FNPAS10Q  

this fails with the following error:   Add-Printer : Parameter set cannot be resolved using the specified named paramete.

How come?

 

 

 

 

A question about ParameterSetName

$
0
0

Hello

I do not believe what I want to achieve is possible with ParameterSetName but thought I would ask here.

Param(

[Parameter(ParameterSetName="A")]$Par1,

[Parameter(ParameterSetName="B")]$Par2,

$Par3,

$Par4

)

Now in the above example Par3 and Par4 belong to 'all' parameter sets. If you select -par1 on the command line -par2 is not available and visa versa, all OK so far.

what I want to do is also make Par3 and Par4 exclusive in other words if I select -Par3 I cannot select -Par4 

But if I do the following

 

Param(

[Parameter(ParameterSetName="A")]$Par1,

[Parameter(ParameterSetName="B")]$Par2,

[Parameter(ParameterSetName="C")]$Par3,

[Parameter(ParameterSetName="D")]$Par4

)

each parameter is now exclusive i.e. if I select one I cannot select any of the others

but if I do the following; as I want to be able to select either Par3 or Par4 when selecting either Par1 or Par2, but if I select Par1 I do not want Par2 (and visa-versa) and if I select Par3 I do not want Par4 (and visa-versa)

 

Param(

[Parameter(ParameterSetName="A")]$Par1,

[Parameter(ParameterSetName="B")]$Par2,

 

[Parameter(ParameterSetName="A")]

[Parameter(ParameterSetName="B")]

[Parameter(ParameterSetName="C")]$Par3,

 

[Parameter(ParameterSetName="A")]

[Parameter(ParameterSetName="B")]

[Parameter(ParameterSetName="D")]$Par4

)

Now the issue with the above is Par3 and Par4 are both members of parameter set names A and B (in other words they have a parameter set name in common, meaning I can now select -Par3 AND -Par4 at the same time (which I do not want)

 

Therefore I can see how you can 'include' a parameter in a given parameter set name, but I do not see how I can exclude a parameter from one set and not another set without affecting your second exclusion (if you see what I mean)

 

Any advise most welcome

 

Thanks

AAnotherUser__

 

 

Display multiple output

$
0
0

Get-EC2Instance |%{ $_.RunningInstance } | select-object InstanceId,@{Name='Key'; Expression={$_.Tag.Key} },@{Name='Value'; Expression={$_.Tag.Value} }

This command displays this output(some of the values can be null($null) in Value column):

InstanceId             Key                           Value

----------             ----                           ------

i-3hwt6346            {qqq:6,rrrr,artt}          {3423:ae,$null,argrarg}

i-5y45yijg5            {ttt:7,rrrr,iii}               {$null,rartrt,55:55}

i-77ar54aer            {aaa:88}                   {$null}

 

how do I display the output in?

InstanceId             Key                         Value

----------             ----                         ------

i-3hwt6346            qqq:6                       3423:ae

i-3hwt6346            rrrr                       

i-3hwt6346            artt                          argrarg

i-5y45yijg5            ttt:7                     

i-5y45yijg5            rrrr                           rartrt

i-5y45yijg5            iii                             55:55

i-77ar54aer           aaa:88              

 

 

 

 

looping SQL Query within Foreach loop

$
0
0

Hi Guys,

I am trying to merge the values I have in an external file with the result from sql query but there is something that sql query keeps only the result from first loop:

Below is the script I have:

$lines = Get-Content 'c:\firstsecondnames.txt'

$DBs = "192.168.1.1"

$DB = "DBA"

$ConnectionTimeout = 90

$QueryTimeout = 90

 

foreach ($ln in $lines)

    {

 

    $vala  = $line.Split(',')[0]

    $valb  = $line.Split(',')[1]

 

    #DB query

     $Query = "select ValC from dbo.PROCESSED_INTERCHANGES where Firstname = '$vala' and middlename = '$valb'

 

        $conn=new-object System.Data.SqlClient.SQLConnection

    $ConnectionString = "Server={0};Database={1};Integrated Security=True;Connect Timeout={2}" -f $DBs,$DB,$ConnectionTimeout

    $conn.ConnectionString=$ConnectionString

    $conn.Open()

    $cmd=new-object system.Data.SqlClient.SqlCommand($Query,$conn)

    $cmd.CommandTimeout=$QueryTimeout

    $ds=New-Object system.Data.DataSet

    $da=New-Object system.Data.SqlClient.SqlDataAdapter($cmd)

    [void]$da.fill($ds)

    $conn.Close()

    $conn.Dispose()

    $valC= $row

 

    $fullname = $vala + $valb + $valC

    Write-Host $fullname

}

It is supposed to give me the output something like:

Firsname1Middlename1LastName1

Firsname2Middlename2LastName2

but, what I get is  :

Firsname1Middlename1LastName1

Firsname2Middlename2LastName1

Please let me know if the description of my problem is not clear, thank you very much for your help


check servers for services and volumes export result as true or false

$
0
0

Howdy,

I am trying to modify a query that writes the result of a query to a csv file.  The script will look for a service and I had it check the startup mode and write that out. But now I need to just check for the service and if the service exists I need to write to a column true and if not exists then it should be false.

I am working on how to get the volume type on the list of servers but if anyone can help me, I need to know if the volumes are ntfs or not. I am sure they are but I have to prove that. 

param (

[string[]]$ServerArray = (Get-Content -Path s:\scripts\serverlist.txt),

[string]$SaveLocation = "s:\scripts\results.csv"

)

if (-not (Test-Path -Path $SaveLocation)) {

New-Item -ItemType directory -Path $SaveLocation

}

$CurrentLogFile = Join-path -Path $SaveLocation -ChildPath 'results.csv'

Foreach ($Server in $ServerArray ) {

"Querying Services for $Server" 

Get-WmiObject win32_service -ComputerName $Server -Filter "Name='wauserv'" | Select Name,

} | Sort-Object "Name" | Export-Csv -Path $CurrentLogFile -NoTypeInformation -Append

}

 

Reading data from CSV file

$
0
0

I know I can get user data like this:  get-aduser 'MyID' | Select-Object name

But how do I display information I've read from a CSV file?   

$read=Import-Csv"U:\reports\ad\Employees.csv"
foreach ($recordin$read) {if ($record-like'*MyID*') {Select-Object$_. starsemail, $_. StarsDepartmentDesc | Write-Host$record

I've tried a few different things with $_.Starsemail (with/without a space).   I need to read a .CSV file and find out certain pieces of information, like email, department ID and department. then, once I have that I need to create a new OU (unless it is already there) based on Department ID and move the user into this new OU.  

Right now our AD is a mess.   We have all users in pretty much 1 OU so it makes it hard to perform many tasks.

 

remove end of a string

$
0
0

I have a .txt file that has the following

Joe@acme.org

Sam@acme.org

if I run the following code it will Add another @acme.org to the end of each line

(get-content"C:\Temp\name.txt") | foreach { $_+'@acme.org' } | set-content"C:\Temp\name.txt"

But if I change the + to a - it fails.  How come?  How do I remove @acme.org from each line?  

I've also tried this and neither one has worked.

 

(get-content"C:\Temp\name.txt") | foreach { $_-replace".*@"-replace",.*"}

$get=get-content"C:\Temp\name.txt"
$get.split('@')[1].split('')[0]

Change Local Administrator password

$
0
0

I have a script that will change the local administrator account on multiple computers withe a get-content command which works great. But I need to have the script randomize the password on each system and then output the server name and password associated with it, which i cannot even think on where to start. Google has not been my friend with it.

Here is my Script:

$computers = Get-Content -path C:\server.txt

$changeuser = "admin account" $password = Get-Content C:\passwords.txt

Foreach($computer in $computers)

{

echo $computer

$user = [adsi]"WinNT://$computer/$changeuser,user" $user.SetPassword($Password)

$user.SetInfo()

 

Where should I start, do not even know where too.

compare 2 cells in Excel

$
0
0

$Read1=Import-Csv"U:\reports\ad\test.csv"
$GetDepartment=$Read1.Department
$GetDesc=$Read1.DepartmentDesc
$GetMail=$Read1.email
foreach ($emailin$GetMail) { $email.remove($email.indexof("@"))}
$email

 

The above code works.  I have 3 columns in my Excel CSV file, Department, DepartmentDesc & Email.   The code above will strip off the @Acme.org from each email which is what I need. So I'm left with JonesSam instead of JonesSam@Acme.org   

In Active Directory I have an OU created for each Department + DepartmentDesc.   So it looks like this:

5023 Graphics

8305 Building Maintenance 

But how do I compare cells in Excel?  I need to do this:

If line two of my  CSV file has 5023 Graphics JonesSam@Acme.org I need to move user JonesSam into the 5023 Graphics OU in AD.

 

 

Viewing all 10624 articles
Browse latest View live