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

How to copy files based on list of array?

$
0
0

Hi Guys,

I need to copy files from sourceA to either destA or destB based on if the filename matches the array of string in an external file or not.

For example:

I have 3 files in SourceA:

CATisNice.txt
DogisPretty.txt
HorseisFast.txt

I have following list of strings in a text file, lets say listA.txt:

Nice
Pretty

Now I need script to check each file and see if its name matches  any string in the  listA.txt

If matches, copy the file to both destA and destB

If not copy only to destB

In the above example, I should see CATisNice.txt, DogisPretty.txt in destA and CATisNice.txt,DogisPretty.txt, HorseisFast.txt in destB

I know only very very basic of powershell and not sure how to loop through the array of value for each object.

Thank you very much for your time and help

Let me know if smething is no clear

 

 

 

 


Need assistance on Start-process

$
0
0

I'm using start-process to add appv package. Normal procedure would be using add-appvclientpackage that returns packageid, versionid etc but if add application using start-process i am not getting return code of add-appvclientpackage.

Direct code: $a = add-appvclientpackage C:\applicationname.appv

write-host $a

Result for above command:

PackageId            : 

VersionId            : 

Name                 : 

Version              : 0.0.0.1

Path                 : 

IsPublishedToUser    : False

UserPending          : False

IsPublishedGlobally  : False

GlobalPending        : False

InUse                : False

InUseByCurrentUser   : False

PackageSize          : 

PercentLoaded        : 100

IsLoading            : False

HasAssetIntelligence : False

 But when i add package using below code, i am not getting above return code of appv client.

$a = Start-Process powershell -Credential DOmain\username -ArgumentList '-noprofile -command &{$result = Add-AppvClientPackage C:\applicationname.appv;$result}' `

 -WorkingDirectory C:\windows\System32\WindowsPowerShell\v1.0 -PassThru

 

Can someone help me how can i get return code of add-appvclientpackage using start-process.

 

Creating a PSUserAgent for Microsoft Office Outlook

$
0
0

So, I am currently trying to retrieve information via "Invoke-WebRequest" from Office 365's autodiscover (https://autodiscover-s.outlook.com/autodiscover/autodiscover.xml). My code currently returns the "600: Invalid Request" error code, which for usual sys administration you'd just go, yep, that means Office 365 autodiscover is working, however I want to retrieve the XML information, and use it to create a .prf file, to then create a mail profile. There seems to be useful bits and pieces across the web for doing this kind of thing via C#, but PowerShell is my choice of tool!

My Current code is:

$uri ="https://autodiscover-s.outlook.com/autodiscover/autodiscover.xml"[xml]$AutodiscoverReq =Invoke-WebRequest $uri -Method post -ContentType"text/xml"-Credential $cred 
$AutodiscoverReq.InnerXML

By monitoring traffic, I have found that I also need to use the User Agent for Microsoft Office Outlook, which looks something like this:

MicrosoftOffice/15.0(Windows NT 6.2;MicrosoftOutlook15.0.4693;Pro)

From my research, I have found that PowerShell current has in-built User Agents, I have included the commands I have run and the results below:

Command:

[Microsoft.PowerShell.Commands.PSUserAgent].GetProperties()|Select-ObjectName,@{n='UserAgent';e={[Microsoft.PowerShell.Commands.PSUserAgent]::$($_.Name)}}

Result:

NameUserAgent-------------InternetExplorerMozilla/5.0(compatible; MSIE 9.0;Windows NT;Windows NT 10.0; en-GB)FireFoxMozilla/5.0(Windows NT;Windows NT 10.0; en-GB)Gecko/20100401Firefox/4.0ChromeMozilla/5.0(Windows NT;Windows NT 10.0; en-GB)AppleWebKit/534.6(KHTML, like Gecko)Chrome/7.0.500.0Safari/534.6OperaOpera/9.70(Windows NT;Windows NT 10.0; en-GB)Presto/2.2.1SafariMozilla/5.0(Windows NT;Windows NT 10.0; en-GB)AppleWebKit/533.16(KHTML, like Gecko)Version/5.0Safari/533.16

Command:

[Microsoft.PowerShell.Commands.PSUserAgent].GetProperties()

Result:

MemberType:PropertyName:InternetExplorerDeclaringType:Microsoft.PowerShell.Commands.PSUserAgentReflectedType:Microsoft.PowerShell.Commands.PSUserAgentMetadataToken:385876515Module:Microsoft.PowerShell.Commands.Utility.dllPropertyType:System.StringAttributes:NoneCanRead:TrueCanWrite:FalseGetMethod:System.String get_InternetExplorer()SetMethod:IsSpecialName:FalseCustomAttributes:{}MemberType:PropertyName:FireFoxDeclaringType:Microsoft.PowerShell.Commands.PSUserAgentReflectedType:Microsoft.PowerShell.Commands.PSUserAgentMetadataToken:385876516Module:Microsoft.PowerShell.Commands.Utility.dllPropertyType:System.StringAttributes:NoneCanRead:TrueCanWrite:FalseGetMethod:System.String get_FireFox()SetMethod:IsSpecialName:FalseCustomAttributes:{}MemberType:PropertyName:ChromeDeclaringType:Microsoft.PowerShell.Commands.PSUserAgentReflectedType:Microsoft.PowerShell.Commands.PSUserAgentMetadataToken:385876517Module:Microsoft.PowerShell.Commands.Utility.dllPropertyType:System.StringAttributes:NoneCanRead:TrueCanWrite:FalseGetMethod:System.String get_Chrome()SetMethod:IsSpecialName:FalseCustomAttributes:{}MemberType:PropertyName:OperaDeclaringType:Microsoft.PowerShell.Commands.PSUserAgentReflectedType:Microsoft.PowerShell.Commands.PSUserAgentMetadataToken:385876518Module:Microsoft.PowerShell.Commands.Utility.dllPropertyType:System.StringAttributes:NoneCanRead:TrueCanWrite:FalseGetMethod:System.String get_Opera()SetMethod:IsSpecialName:FalseCustomAttributes:{}MemberType:PropertyName:SafariDeclaringType:Microsoft.PowerShell.Commands.PSUserAgentReflectedType:Microsoft.PowerShell.Commands.PSUserAgentMetadataToken:385876519Module:Microsoft.PowerShell.Commands.Utility.dllPropertyType:System.StringAttributes:NoneCanRead:TrueCanWrite:FalseGetMethod:System.String get_Safari()SetMethod:IsSpecialName:FalseCustomAttributes:{}

My Question is, how can I create a PSUserAgent object myself for outlook? And use it to retrieve the information I need?

If anyone can see any issues with what I'm attempting or has any advice, that would be greatly appreciated.

wait for a windows to appear ?

$
0
0

A small vendor gave us some software to install and they did not provide any silent way to install it.  -s, -q, /q, -q, -silent etc... none of those are available.   So I need to automate the installation.  I did this using PowerShell but I need to make my code smarter.   How do I "wait" for a window title to appear?

$wshell = New-Object -ComObject wscript.shell;

$wshell.AppActivate('My Window Title Here')

I use Start-Process to call the .EXE in question and yes I can use sleep 'x' but that is crude.  I want to have my code loop until this window title appears.

 

 

 

 

force window to be active and on top?

$
0
0

I call an .EXE, I then disable the mouse and keyboard.   The .EXE that is called throws up a dialog window that I try to activate.    This is running from the RUN key in the registry.

$wshell=New-Object-ComObjectwscript.shell;
$wshell.AppActivate('Alaris® desktop configuration tool')

The issue I'm seeing is although the dialog window does appear my script never clicks the "Next" button since for some reason the window does not have focus.    But, if I run this manually it all works.  Being called from the RUN key seems to be the issue that causes the focus problem.

Is there another command that will force a window to be on top and the active window?

 

test-connection fails because multiple IP's registered in DNS for computer

$
0
0

Hi

Just started to learn PowerShell, created my first practical script which pings a list of desktops and laptops and if they are reachable exports out the remaining c: drive free space into a .csv file.

All is well until I realised a lot of laptops are failing to return any data because they are not reachable using test-connection even though I know the laptops are plugged into the network.

This seems to be because there is more than one IP address registered in DNS for some laptops. The second IP is from the a recent VPN connection the user initiated when they were working from home which remains registered in DNS for 7 days. If I do a NSLOOKUP on the hostname I can see both IP addresses, the live LAN IP as well as the previous VPN IP. It seems when test-connection pings the machine it sometimes returns the VPN IP which times out resulting in a failed ping.

Question is, is there a way if test-connection fails to check for a secondary IP registered in DNS and then ping that giving me a reachable device and a more complete disk space report?

 

Many Thanks Big Smile

Print list of (mostly) empty folders - script optimization, elegance

$
0
0

I pieced the following together to "scan" a folder structure and output line-terminated paths of folders that contain no files, directly or indirectly. The script expects an argument of the top-level or root folder to check. It took a few minutes to run with a network share as target (contains 1,982 folders and 13,970 files). If you have tips for optimizing or a more elegant / different approach to suggest, I'm interested!

param([string]$PathRoot="");
[System.Collections.ArrayList]$emptyDirs=Get-ChildItem$PathRoot-Recurse|Where-Object {$_.PSIsContainer};
$emptyDirs.Insert(0, (Get-Item$PathRoot));
$dirsWithFiles=Get-ChildItem$PathRoot-Recurse|Where-Object {$_.PSIsContainer -and$_.GetFiles().Count}

for ($i=0; $i-lt$dirsWithFiles.length; $i++) {
    for ($j=0; $j-lt$emptyDirs.Count; $j++) {
        if ($dirsWithFiles[$i].FullName -like ("{0}*"-f$emptyDirs[$j].FullName)){
            $emptyDirs.RemoveAt($j);
            $j--;
        }
    }
}

$emptyDirs|ForEach-Object {$_.FullName};

 

 

 

VB message boxes and outputs?

$
0
0

Normal 0 false false false EN-AU X-NONE X-NONEHow do I write a powershell script which brings up a VB Script message box, with Yes, No and Cancel buttons.  Executing a different action for each button press?


using the -AsHashTable and -AsString parameters with Group-Object cmdlet

$
0
0

Hello 

I have seen a few examples (cannot lay my hands on one now unfortunately) where people has used -AsHashTable and -AsString with the Group-Object cmdlet

can someone place explain a bit more about these two parameters e.g. do they always need to be used together or can they be used separately

can anyone give me some examples of when and where these two parameters would come in handy e.g. when and why to use

 

Thanks

AAnotherUser__ 

 

Compressing&Decompressing Sites Using Powershell Command/Script.

$
0
0

What powershell command/script would be needed to tell a browser to send a note on the fly to compress a requested site by eliminating unnecessary bits in order to reduce the site's size to one third and decompress the site after reaching the browser that called it?

How to best handle "No matches found"

$
0
0

Hi All,
Am new to PowerShell and still learning my way about.

I am running the following snippet of code ...

$event= Get-EventLog -LogName Security -ComputerName [DCServer] -InstanceId 4740 -Newest 1 |
   Select TimeGenerated,ReplacementStrings,"Account name","Account Domain","Caller Computer Name" |
   % {
     New-Object PSObject -Property @{
      "Account name" = $_.ReplacementStrings[-7]
      "Account Domain" = $_.ReplacementStrings[5]
      "Caller Computer Name" = $_.ReplacementStrings[1]
      Date = $_.TimeGenerated
    }
   }

My question is how should I best handle this when it returns nothing?

Example:

Get-EventLog : No matches found
At line:1 char:1
+ Get-EventLog -LogName Security -ComputerName [DCServer] -InstanceId 4740  ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (:) [Get-EventLog], ArgumentException
    + FullyQualifiedErrorId : GetEventLogNoEntriesFound,Microsoft.PowerShell.Commands.GetEventLogCommand

Thanks in advance.

Cheers, Cameron

Reverse-engineering a PS script

$
0
0

So, I'm reverse-engineering a PS script to add users to AD.

 

I see the script is organized like an old Pascal, or C program.

Some global variables at the top, (actually, that is what I want to ask you about).  Followed by some number of functions,and finally a main body.

What I would like to inquire about are the first two lines of code, they are:

 

ReadExtendedAttributes,  WriteExtendedAttributes

WriteAttributes, Write, Delete, ReadPeremissions, Read,

 

So, what am I looking at?    They don't look like variables, or booleans.   As a group, they look like permissions?

But, what does it mean for these "permissions" to be listed as the first two lines of a script?

 

Thank You.

Regards,

-DW

Show message box (form) while script is running

$
0
0

Hello,

I´m working on a installtion script which should install a .msi package and while the installation is running the user should see a message box (form) "installation running".

My problem is to get the message box (form). If I use "$Form.ShowDialog()" the script will stop as long as the form is open. And if I use "$form.Show()" I cann´t see the label text because the label is transparent.

Here is my script:

    Add-Type -AssemblyName System.Windows.Forms

    $Form = New-Object system.Windows.Forms.Form
    $Form.Text = "Installation"
    $Form.AutoSize = $True
    $Form.AutoSizeMode = "GrowAndShrink"
    $Font = New-Object System.Drawing.Font("Times New Roman",18 [System.Drawing.FontStyle]::Italic)
   
    $Form.Font = $Font
    $form.FormBorderStyle = [System.Windows.Forms.FormBorderStyle]::FixedSingle

    $handler_form_Load = { $form.Location = New-Object System.Drawing.Point(600, 200) }
    $form.add_Load($handler_form_Load)
 
    $Label = New-Object System.Windows.Forms.Label
    $Label.Text = "Installation running...."
    $Label.AutoSize = $True

    $Form.Controls.Add($Label)

    # $Form.ShowDialog() | out-null
    $form.Show() | out-null

    #give the form focus
    $form.Focus() | out-null

    # Here the installation should start

    $form.Close()

 

Regards, Martin Fischer

 

Report of members of local Administrators group

$
0
0

I found this here: (http://powershell.com/cs/media/p/376.aspx)

  1. cls 
  2. $ErrorActionPreference="SilentlyContinue" 
  3. Get-Content (ENTER PATH TO YOUR INPUT FILE HERE) | foreach
  4.     [ADSI]"WinNT://$_/administrator" | select ` 
  5.     $(Name="Account";Expression={($_.PSBase).Path}}, ` 
  6.     $(Name="Password Set";Expression={(Get-Date).AddSeconds(-($_.PasswordAge)[0])}}; ` 
  7.     $(Name="PasswordAge (Days)";Expression={[int]((4-.PasswordAge)[0]/86400) }}, ` 
  8.     $(Name="Last Logon";Expression={$_.LastLogin}}, ` 
  9.     $(Name="Days Since Last Logn";Expression={ ` 
  10.     (New-TimeSpan-start ($_.LastLogin[0]) -end (Get-Date)).days}}} ` 
  11. | Export-csv (ENTER PATH TO YOUR OUTPUT FILE HERE) -notypeinformation 

The $'s in the SELECT statement need to be @'s... That corrected, I'm trying to get to run so I can report on the local administor account - by SID.  Our local admin accounts are renamed depending on department.   Also to run against all (local account) members of the builtin administrators group.

I've been able to dump the members, but am having trouble putting the two halves together.  

 

Script msg-ing list of PCs fails on some

$
0
0

Hi, I'm using PowerShell from my Microsoft System Center Configuration Manager server (SCCM) to message a group of machines via pop-up. The following script works except for the machines that are powered off...and others...for some reason.

$ComputerList=Get-WmiObject-ComputerNameSCCMSERVERNAME-Namespace"ROOT\SMS\site_XXX"-Query"SELECT * FROM SMS_FullCollectionMembership WHERE CollectionID='XXXXXXXX' order by name"|selectName

 

ForEach

 

 

 

($ComputerObjectIn$ComputerList){

icm

 

 

-computername$ComputerObject.Name -scriptblock {msg*"This is a test. Click OK."}

}

There are 110 computers in the collection. The script works perfectly with a smaller collection, say 5 PCs. But when I Try a larger one, some boxes don't display the pop-up. And these boxes work perfectly when I use a smaller collection (and the same script). Is there a limitation here I'm unaware of? Any thoughts? Advice?


Combine and arrange text files

$
0
0

I am using the get-content and sort-object -unique cdmlets to combine text log files via:

(Get-Content .\*ninite.txt) | sort -unique | Set-Contentinstallreport.txt

Example text files are uploaded here.  The unique switch removes duplicates but it also rearranges the text lines.  I would like to have the single OK string be at the top of the lest in the final exported text file.  Do I need to save each line to a hash and rearrange that way first?

Append and overwriting in a CSV file

$
0
0

 

is it possible to append new data to a CSV file, but only add the new information ?

for exp

the existing CVS file has 1,2,3,4 then the new file has 1,2,3,4,5. I really would like 1-4 to remain unchanged but 5 is add. as well as if the CVS file has 1,2,3,4 in it and the source of the CSV file no longer has 2 in it , I would like 2 to remain on the CSV and any new information to still be added

Require User Details from AD

$
0
0

Hello Team,

Require your help with my AD. We have around 4000+ user accounts configured on our AD with below extra parameters configured :

1. Description

2. Expiry Date

I need to get below details for my user accounts :

Detailed AD user data with userid, expiry date, Description, Account State(Enabled/Disabled), account creation date.

It would be a great help from you all.

With Regards,

Rohit

 

Piping Get-ADUser to Select-Object

$
0
0

Still really new to PS and scripting in general but I have been having a lot of fun learning over the last few months. I have a small issue when piping properties to Select-Object and I can't figure out what I am doing wrong, though I'm sure it's simple. Any insight is greatly appreciated!

 

This is the snippet I am having trouble with, I understand that using Read-Host is considered bad form, and I would prefer to build this out into a function with parameters, but this is how the folks who sign off on this want it so the dude abides.

 

$Target=Read-host"Enter the SamAccountName of the user you want to transfer"

$Verify=Get-ADUser-Identity$Target-Properties*|Select-Object-ExpandPropertyDisplayName,SamAccountName,CanonicalName,Description

 

It gives a ParameterBindingException "Select-Object : Cannot convert 'System.Object[]' to the type 'System.String' required by parameter 'ExpandProperty'" error.

I know Get-ADUser is passing Management.ADUser objects and based on the error -expandproperty wants a System.String, so then I tried piping it to Out-String first, before Select-Object to convert to System.String

$Verify=Get-ADUser-Identity$Target-Properties*|Out-String|Select-Object-ExpandPropertyDisplayName,SamAccountName,CanonicalName,Description

 Still the same error! So then I decided I should confirm Out-String converted the objects to System.String

 

$Verify | Get-Member

 

 

And as expected, $Verify now contains System.String objects. So at this point I know the following to be true:

$Target=Read-host"Enter the SamAccountName of the user you want to transfer"

Gives me a System.String object

$Verify=Get-ADUser-Identity$Target-Properties*|Out-String

Gives me a System.String object

$Verify=Get-ADUser-Identity$Target-Properties*|Select-Object-ExpandPropertyDisplayName,SamAccountName,CanonicalName,Description

Gives me an error                           

$Verify=Get-ADUser-Identity$Target-Properties*|Out-String |Select-Object-ExpandPropertyDisplayName,SamAccountName,CanonicalName,Description

Gives me an error

 

However,

Get-ADUser-IdentityTest.User-Properties*|Select-Object-ExpandPropertyDisplayName,SamAccountName,CanonicalName,Description

returns the output I expect. Where is my disconnect? Thank you in advance for the help!!

 

Updating ADusers from CSV

$
0
0

I got this script working the way I wanted, here's final version:

clear
$users = Import-CSV "C:\x.csv" -delim ';' -encoding UTF8
$ou = Read-Host 'Which OU to update'
Foreach ($user in $users) { 
    if ($user.'SamAccountName') {
  $aduser = Get-ADUser -Filter "SamAccountName -eq '$($user.samaccountname)'" -SearchBase "OU=$ou,OU=ENEA-SERWIS,DC=enea,DC=pl"
  }
    if ($aduser) {
  Write-Host "Updating active directory user: " -nonewline; Write-Host $aduser.name -ForegroundColor Yellow
   $userprops = Get-Member -InputObject $user -MemberType NoteProperty
  Foreach ($userprop in $userprops) {
   $propname = $userprop.name
   $propvalue = $userprop.Definition.Split("=")[1]
   if ($propvalue) { if ($aduser.$userprop -eq "") -or ($aduser.$userprop -eq $null) {
           #splat the values into a parameters hashtable
           $parms = @{$propname = $propvalue}
           Set-ADUser $aduser @parms}
           }
   } else {
    Write-Host "Property " -nonewline; Write-Host $propname -ForegroundColor Magenta -nonewline; Write-Host " was empty for user " $user.SamAccountName " - AD User property not changed"
   }
  }
 } else {
  Write-Host "Couldn't find a user in active directory to match CSV User:"  $user.SamAccountName
 }
 #Clear the aduser variable in case we don't find one next time round.
 Clear-Variable aduser
}


 

Now... I messed it up a bit :) There is a small catch, I was told about later on (to late, and got bit messy). I only had to update EMPTY AD fields. If there is any value set to some user field/attribute it should be left as it is, even if in CSV file it's different. I replaced AD values with those from CSV and some applications stopped working - they need specific values in some fields, even if they dont make sense. So only updating empty ones.

So, my plan was to just add extra IF condition, and check if given field is $null or "", but it doesn't work like it should. I bet there's just a small detail I'm missing, which prevents it from doing what it should do. It doesn't give me any error, but also doesn't update like it should.

Above is working script which updates all users, checks for empty fields in CSV file. But I need extra check to it. I've added in bold an extra condition I thought will be enough. But seems like that $aduser.$userprop is completely wrong, unsure how to handle it..

I'm real just a beginner with scripts and Powershell in general, but got this silly assignement to update 400+ accounts and thought I'll spend even few days doing it right (via script) instead brutal forcing tchem all one by one. But I got problems with basic concepts of scripting sometimes and it's hard for me to figure out how to fix my mistake.

Please.. help ?

Viewing all 10624 articles
Browse latest View live