Quantcast
Channel: Windows PowerShell forum
Viewing all 21975 articles
Browse latest View live

Compare folder structures and report differences

$
0
0

I have a large amount of folders from which the data needs to be copied into a new folder structure.

before I start, I would like to compare each folder with the new structure and report the differences.

I am not interested in the files, only the folders.

is there a way to achieve this ?


Powershell script to find PC's that have dropbox installed

$
0
0

I have been using the get-installedapps.ps1 a ton for finding different apps that are installed on my domain. 

I am now trying to find any computers that has dropbox installed. Dropbox doesn't put it's unstall string in the normal place- it looks like it is in the HKEY_Users hive.

Does anyone know how I could scan my domain for any PC's that has dropbox?

 

Thanks in advance!

Get-Eventlog script to return certain parts of -Message

$
0
0

Hello,

So i run this script against one of my Backup servers 

$Machine = "Machine1"Get-Eventlog -Logname Application -Source "Backup Exec" -EntryType Warning -ComputerName $Machine  -After (Get-Date).AddDays(-1) | Select-Object -ExpandProperty message


Output

Backup Exec Alert: Job Completed with Exceptions (Server: "machine1") (Job: "Machine1 Daily INC Backup") The job completed successfully. However, the following conditions were encountered: 86 files were skipped.

My issue is I only want my script to return a certain part of the output. i.e.

(Server: "machine1") (Job: "Machine1 Daily INC Backup") The job completed successfully.

Does anyone know I would go about achieving this? converting it to a string or trimming does't seem to work :(

Thanks in advance

J


MD5 Hash and File Check on 2012+ Servers

$
0
0

Hello Gurus!

   I've been working on a script for the past few weeks to check specific
paths for certain file extensions and doing comparisons to the previous days
check to find files that have been added/removed and then do a hash check on the
remaining files to make sure they haven't changed since the previous day. I can
get parts of it working but my reliance on compare-object for my comparisons is
changing my output so I can no longer pipe it into cmdlets like Get-FileHash. I
could use some help!

   Here is what I'm specifically trying to do. First I am scanning the
following paths for *.exe, *.dll, *.bat, *.vbs, *.cmd files.

Path1 - C:\ (non-recursive)

Path2 - C:\Windows (recursive)

(Code Example)

$include=@("*.dll","*.exe","*.bat","*.cmd","*.vbs")
$files = @(Get-ChildItem -Path C:\* -Include $Include)
$files += @(Get-ChildItem -Path $env:WINDIR\* -Include $Include)

(/Code Example)

Once I have the file list stuffed in a variable (Is Get-ChildItem The best
way to do this?) I then compare it to the previous days file list (stored in CSV
form and imported into a variable) and compare the two variables to find files
that have been deleted or added.

(Code Example)

$previous = Import-CSV C:\Scripts\PrevFiles.csv

$current = $files | Get-FileHash -Algorithm MD5 | Select-Object Path,Hash

$FD = Compare-Object $previous $current -Property Path | Sort-Object Path | Select-Object -Property Path,SideIndicator

(/Code Example)

Once those files have been identified, they are exported to an easily
readable text file:

FileChanges.txt

c:\Windows\driver.com    File Deleted!

c:\GPOLogger.dll             File Added!

Now I run another compare against the current and previous file lists to find
all the files paths that match and create a new file list of all the matched
paths that is stored in a new variable.

I now run that variable of the matching path file list piped into
Get-FileHash and assign it to a new variable so I have the file path and hash
for each file. I then import the CSV from the previous days FileHash output and
compare them looking for changes in Hash. Once the files with changed hash are
identified they are appended to the FileChanges.txt file in an easily readable
format.

FileChanges.txt

c:\Windows\driver.com       File Deleted!

c:\GPOLogger.dll                File Added!

C:\Windows\explorer.exe    Hash Changed!

Once complete, I check the FileChanges.txt for any content, if none send an
e-mail saying no changes. If there is content in FileChanges.txt I send a
different e-mail alerting people of the changes and attach the FileChanges.txt
file to the e-mail.

I then write the current file list to CSV and overwrite yesterdays file list
so it can be read tomorrow as the "previous day". I do the same thing for the
current hash/file list.

------

I thought this was going to be painless until I realized Compare-Object
changes the data type so I can no longer feed it's output to Get-FileHash. While
I understand certain parts of Powershell very well, this is not one of them. Can
anyone get me over the hump of generating file lists that I can compare and
output new file lists that can be fed to Get-FileHash? Or if you have a better
idea how to structure the data and comparisons, I'm all ears!

Thanks all!

Powershell HASH

$
0
0

I created thisscriptinPowershellto read aDBrecord andcreate ahashof itsaltyand insert it backin atable,goodscriptworksfine the wayI need,butwhat sticksis the delay9 millionrecordtwo days.I needifanyone has anycommand thatcouldmake it fasterto things.

Whohas littlerecord andwant to usethis scriptare comfortableit works.

$user = "user"
$pwd = "pws"
$database = "bdd"
$SqlServer = "round"
$SqlLogs = "T_Powershll"
$Date = (Get-Date -format g)
$SqlConnection = New-Object system.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString ="Server=$dataSource;uid=$user; pwd=$pwd;Database=$database;Integrated Security=False;"
$SqlConnection2 = New-Object system.Data.SqlClient.SqlConnection("Server=$dataSource;uid=$user; pwd=$pwd;Database=$database;Integrated Security=False;")
 
$seq=1
$fim=9561421
While ($seq -le $fim){
$SqlCommandText = "Select Cartao from T_Powershll_base where Id_seq= $seq "
$SqlConnection.Open()
$SqlConnection2.Open()
$SqlCmd = New-Object Data.SqlClient.SqlCommand($SqlCommandText, $SqlConnection)
$sqlcmd2 = $SqlConnection2.createcommand()
$Reader = $SqlCmd.ExecuteReader()
$SqlData = @( )
while ($Reader.Read())
{
 $SqlData += "" | Select-Object `
 @{ n = 'Cartao' ; e = { $Reader["Cartao"].ToString() } }
}
$Reader.Close()
$sha1 = New-Object System.Security.Cryptography.SHA1CryptoServiceProvider;
$sha1.Initialize();
$Salgado="710000hhgiiAAAhhhhooohzaqnpa
          epszx7w2soPmdfapa)gbbakkazwq
    "
$cart=$SqlData.Cartao
$cart2=[System.Text.Encoding]::ASCII.GetBytes($cart.PadRight(32,'_'));
$lim4=[System.Convert]::FromBase64String($Salgado.ToString());
$ab =$sha1.ComputeHash($cart2+$lim4);
$HASH="{0}" -f [system.BitConverter]::ToString($ab)-replace "-",""
$sqlcmd2.CommandText = "INSERT INTO $SQLLogs (Cartao, Cartao_Hash) VALUES ('$($SqlData.Cartao)', '$($HASH)')"
$Results = $SqlCmd2.ExecuteNonQuery()
$seq++
$SqlConnection.close()
$SqlConnection2.close()
}

TKS.

Constrained Delegation For Remote Powershell Sessions

$
0
0

Consider the case of a client (let's call it Client) doing a remote Powershell session to a server (ServerA). In this Active Directory environment, the client has full administrative permissions over ServerA. To create the session, the client opens a Powershell console and types:

$ps = New-PSSession -ComputerName ServerA
Enter-PSSession $ps

From this point, the client wants to be able to open a different remote Powershell session to another server (ServerB). Again, he's having administrative permissions over this server as well. If he goes ahead and uses the cmdlet below:

$newPS = New-PSSession -ComputerName ServerB
...this won't work by default due to the Kerberos double hop issue.

A way to make this work is enable delegation for the Client AD account (by adding a dummy SPN and also making sure theAccount is sensitive and cannot be delegated isn't enabled), and turn on unconstrained delegation for theServerA computer account in Active Directory. After this is done, as soon as the 1st remote PS session is entered, issuing a 'klist' will reveal a Kerberos TGT for Client, with the 'forwarded' flag set. The 2nd remote PS session can be made without any issues now to ServerB.

However, in order to make this more secure, as to not have ServerA being able to act on behalf of Client to any target machine, but only againstServerB, constrained delegation can be used. So the ServerA's Delegation tab in AD is changed as to contain only thehttp/ServerB.fqdn (since we're using Powershell remoting). The problem is that trying to initiate the 2nd connection fails just as in the original case (logon session does not exist). Checking things further, I've noticed that after the 1st session is entered, issuing a 'klist' only reveals an http/ServerB.fqdn Kerberos ticket, and no longer any Kerberos TGTs. However reading the documentation surrounding constrained delegation (namely the S4U2Proxy component)here, it doesn't look as the TGT should be present there.

The question is why cannot constrained delegation be used here or more likely, what is it I'm doing wrong ?

Note that CredSSP is a mechanism that I wouldn't want to use here. Also, even though this entry contains a lot of Active Directory information, I thought it would be relevant for the Powershell community to post here as opposed to the Active Directory section. If this should be moved, please let me know.

"get-date -format u" returns local time, not UTC

$
0
0

Greetings,

I'm struggling with converting and formatting date/time with the get-date cmdlet ...

According to https://technet.microsoft.com/en-us/library/ee692801.aspx

   get-date -format "u"

should return UTC in the format "yyyy-MM-dd hh:mm:ssZ" with the appending Z to denote "Zulu" or UTC time, but on my system (Windows 8.1/64 bit, Powershell 4.0) it always returns the local time.

Example: It is 20:53 local time (GMT+1, Germany) for me now, so that is 19:53 UTC.

get-date -format "U" correctly returns

Freitag, 6. Februar 2015 19:53:00

but get-date -format "u" returns

2015-02-06 20:53:00Z

whereas it *should* really return 2015-02-06 19:53:00Z

Am I right, and is this a bug in get-date, or am I misunderstanding something?

Thanks for any comments

Andreas

Help w/ CSV Parsing

$
0
0

Hi Everyone,

I'm working through a test to see how CSV parsing in relation to folder and subfolder creation works. The script I have is as follows:

$File = "C:\Projects\Folders\folders.csv"
$Data = Import-Csv $File
$Base = "C:\Projects\Folders\Test\"
foreach($line in $Data) {
    $topFolder = $Base + $line.Base
    if (!(Test-Path $topFolder)) {
        New-Item $topFolder -type directory
    }
	if (!(Test-Path "$topFolder\$line.Sub2")) {
		New-Item "$topFolder\$line.Sub2" -type directory
	}
	if (!(Test-Path "$topFolder\$line.Sub2\$line.Sub3")) {
		New-Item "$topFolder\$line.Sub2\$line.Sub3" -type directory
	}
}
Write-Host "Folder created"

And the CSV looks like this:

Base,Sub1,Sub2
Folder 1, Subfolder 1,Subfolder 2

Now, I'm getting the CSV read just fine, however I'm getting stuck on building out the subsequent subfolders and end up with a "Folder 1" directory in my $Base which then gets populated with directories that look as such:

C:\Projects\Folders\Test\Folder 1\@{Base=Folder 1; Sub1=Subfolder 1; Sub2=Subfolder 2}.Sub1\@{Base=Folder 1; Sub1=Subfolder 1; Sub2=Subfolder 2}.Sub2

@{Base=Folder 1; Sub1=Subfolder 1; Sub2=Subfolder 2}.Sub1 being the name of the first folder in the topmost folder (Folder 1)

and @{Base=Folder 1; Sub1=Subfolder 1; Sub2=Subfolder 2}.Sub2 being the nested folder within that subfolder.

What am I doing wrong here? I need the script to parse the CSV, create the "Base" folder, then populate the subfolder structure from Sub1 under that and then in each of those Sub1 folders I need to populate the directory structure with the folder names from Sub2.

It seems pretty straightforward but I'm obviously missing something.


Michael Kaminski


Some groups show no members in Get-ADGroup

$
0
0

So I have a question about strange PowerShell behavior with Get-ADGroup. If I use it on a group I created, I can get members just fine. But on some (not all) built in groups, includingDomain Users, it returns nothing. See:

PS C:\> Get-ADGroup -Filter * -Properties * | Where {$_.name -eq "Iron Throne"} | Select -ExpandProperty members
CN=robert,OU=Baratheons,DC=seven-kingdoms,DC=local
CN=daenerys,OU=Targaryens,DC=seven-kingdoms,DC=local
CN=margaery,OU=Tyrells,DC=seven-kingdoms,DC=local
CN=joffrey,OU=Baratheons,DC=seven-kingdoms,DC=local
CN=Cersei Lannister,OU=Lannisters,DC=seven-kingdoms,DC=local

PS C:\> Get-ADGroup -Filter * -Properties * | Where {$_.name -eq "Domain Users"} | Select -ExpandProperty members

PS C:\> 

They show up fine in Active Directory Users and Computers. This is on a Win2012R2 DC as Administrator. Anyone knows why?

'A positional parameter cannot be found that accepts argument '$null'.

$
0
0

I am trying to execute below PowerShell script to audit a file share for filenames starting with S. This script is executed by a SQL job every 10 seconds.

Script also tries to create a Log file each day and appends the data.

Script:

$svcs = Get-ChildItem -Path "\\XYZ\1100\ARCHIVE" | ?{ $_.name.StartsWith("S") } $filepath = "D:\Audit_1100\" + (date -f yyyy-MM-dd) + "_ArchiveAudit.txt" $svcs | select-object LastWriteTime,Name | sort LastWriteTime | out-file -append $filepath

Problem : I see below error while executing the script. Could you please advise what is missing here ?

A job step received an error at line 1 in a PowerShell script. The corresponding line is '$svcs = Get-ChildItem -Path "\\XYZ\1100\ARCHIVE" | ?{ $_.name.StartsWith("S") } $filepath = "D:\Audit_1100\"+ (date -f yyyy-MM-dd) + "_ArchiveAudit.txt" $svcs | select-object LastWriteTime,Name | sort LastWriteTime | out-file -append $filepath'. Correct the script and reschedule the job. The error information returned by PowerShell is: 'A positional parameter cannot be found that accepts argument '$null'.  '.  Process Exit Code -1.  The step failed.

Additional Error Details :

Where-Object : A positional parameter cannot be found that accepts argument 'D:\Audit_1100\2015-02-06_ArchiveAudit.txt'.

At line:1 char:63

+ $svcs = Get-ChildItem -Path "\\XYZ\1100\ARCHIVE" | ?{ $_.name.ToLower ...

+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    + CategoryInfo          : InvalidArgument: (:) [Where-Object], ParameterBindingException

    + FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.WhereObjectCommand


Powershell script to compare files.

$
0
0

Hi...I am looking for a script to compare 2 different .CSV files to check if there is any name entry to pop-up a message with the entry name. 

Also we have to do this regularly, hence I would like to have a pop-up message to enter the 1st file name and then enter the 2nd file name. Then would like to compare the values & give out the message with the similar entry. 

Can you please help me in that or point to the example script. Hoping to hear from you.


VT

Apostrophe within a sngle quote string

$
0
0

Hi,

I am contructing a query where the email address has to be contained within single 'quotation' marks.  am having an issue where a user has an apostrophe in their name. I have tried to escape the character using the $variable.Replace("'","`'"). However becasue the email address is already within the single quotation marks it doesnt seem to be working. Does anyone have any idea how i can get around this issue.

Thanks

Michael.

Combine 6 .xlsx files to into 1 .xlsx file with 6 sheets

$
0
0

Hello

Is something like this possible to do with powershell? I'm using excel 2013. The script should create the 1 excel file by itself.

Thank you.

prevent PS script contents from being read

$
0
0

Hello

if we have created a valuable script & we are going to deliver it to a company so that they be able to run it but unable to see its contents & our code, is there any solution?

thanks

Powershell script to install Pidgin

$
0
0

Hello,

I want to install Pidgin in all the computers on the network and I want to do it via Powershell. I modified a script that i found and it looks like this:

$computers = Get-Content "C:\Users\administrator.INTERN\Desktop\Scripts\Pidgin\computers.txt"

foreach ($computer in $computers) {


#The location of the file
    $Install = "\\voyager\Software\015 Messenger Clients"

#The Install string can have commands aswell
  $InstallString = "$Install\pidgin-2.10.11-offline.exe"

	([WMICLASS]"\\$computer\ROOT\CIMV2:Win32_Process").Create($InstallString)
#Output the install result to your Local C Drive
	Out-File -FilePath c:\Users\administrator.INTERN\Desktop\Scripts\Pidgin\installed.txt -Append -InputObject "$computer"}

But when i execute it i get this messages:

Cannot convert value "\\192.168.9.104\ROOT\CIMV2:Win32_Process" to type "System.Management.ManagementClass". Error:"The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)"
At C:\Users\administrator.INTERN\Desktop\Scripts\Pidgin\install pidgin.ps1:18 char:2+     ([WMICLASS]"\\$computer\ROOT\CIMV2:Win32_Process").Create($InstallString)+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ CategoryInfo          : InvalidArgument: (:) [], RuntimeException+ FullyQualifiedErrorId : InvalidCastToWMIClass

I know nothing about scripting.

Also if it is posible , does anyone knows hot to make it so Pidgin uses the windows credentials???

Thanks


migrating on premise site collections to SharePoint online using powershell

$
0
0

Hi folks,

Intention:-migrating on premise site collection to SharePoint online.

Is there any power-shell script or list availabe products.

Please give idea and let me know that script.

Thanks,

Powershell and SCCM Task Sequences

$
0
0
Does anyone know if there is any way to modify the sequence propery of an sms_tasksequencepackage object with Powershell?  I am trying to migrate a task sequence from one site to another and want to programatically update the package IDs to match what is on the destination site.  I have everything down except the ability to actually write the value of the xml string to the sequence property.

When I connect to the wmi object directly, I can't even get the sequence property.  It just comes back blank.  When I use the get-cmtasksequence cmdlet, I can get the value, but I can't find any way to modify it and write it back.  I have tried using a combination of the two to get the sequence value with the cmdlet and then try to write it back to the wmi object, but that won't take either.

I have even tried running an export, extracting the zip, and modifying the xml from there to reimport, but there is some kind of psmdcp hash value that appears to be rejecting it when I try to reimport.

It seems like there must be some way unless Microsoft has just made the property read only via WMI and is using some proprietary hash value to prevent changing the task sequence between export and import.  I'd love to hear anyone's input on this.

Password RegEx Check

$
0
0

I'm trying to use RegEx to validate the password strength for a Cisco UCS password. Due to the complexity requirements I'm having a bit more trouble than I expected. This is what's expected:

 If you enable the password strength check for locally authenticated users, Cisco UCS Manager rejects any password that does not meet the following requirements:

 Must contain a minimum of 8 characters and a maximum of 64 characters.
 Must contain at least three of the following:
 1) Lower case letters
 2) Upper case letters
 3) Digits
 4) Special characters
 Must not contain a character that is repeated more than 3 times consecutively, such as aaabbb.
 Must not be identical to the username or the reverse of the username.
 Must pass a password dictionary check. For example, the password must not be based on a standard dictionary word.
 Must not contain the following symbols: $ (dollar sign), ? (question mark), and = (equals sign).
 Should not be blank for local user and admin accounts.

That comes from this documentation and and help is greatly appreciated.
Thanks

Adam

Ignore the powershell execution policy on remote servers

$
0
0

I have a powershell script that I need to run remotely on around 500 servers. The script runs successfully on few of the servers but on few it fails because of the execution policy. The script fails on the servers in which the execution policy is set to either "Restricted" or "bypass".

Is there a way to ignore the execution policy on the servers so the script can be executed successfully?



Dynamic Access Control from PowerShell

$
0
0

Hi Guys 

Please I need your help, I am working with AD Dynamics Access Control (AD DAC)  and Windows Powershell (PS), the Idea is create a menu for AD DAC in PS, Everything is OK but I have a problem when I create  a new  ClaimType, because from AD DAC windows  Menu you can select an AD Attribute and there is a Column naming  "Value Type" , but in my Script I Don't know how to get this to show in OUT-GridView, I dont know what is the correct property. 

My Code:

Get-ADObject -SearchBase ((Get-AdRootDSE).SchemaNamingContext) -SearchScope 1 -filter *  -Property name, Ldapdisplayname | out-gridview -outputmode Single

Sorry But I can't put my image here 

Thanks in advance 

Viewing all 21975 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>