Quantcast
Channel: The Official Scripting Guys Forum! forum
Viewing all 15028 articles
Browse latest View live

O365 Search Mailboxes to determine read status of a specific email

$
0
0

Howdy All - 

Can anyone point me as to how you can search a single or multiple mailboxes for a specific email by sender or subject to find out if the email was read?

I have scoured the net and can not find anything related to this for O365 or even Exchange 2013.

Thx!

Domran


Powershell can't display all the property

$
0
0

Hi Guys

  I'd like to query the ConnectionInfo property from the Win32_OfflineFilesItem class

Class Win32_OfflineFilesItem

{

  string                                        ItemPath;

  string                                        ParentItemPath;

  string                                        ItemName;

  uint32                                       ItemType;

  Win32_OfflineFilesFileSysInfo      FilesSysInfo;

  Win32_OfflineFilesPinInfo            PinInfo;

  Win32_OfflineChangeInfo            ChangeInfo;

  Win32_OfflineConnectionInfo  ConnectionInfo;

  Win32_OfflineSuspendInfo           SuspendInfo;

  boolean                                      Encrypted;

  boolean                                      Sparse;

};

  I run this command

  Get-WmiObject -Class Win32_OfflineFilesItem

=========Below are parts of the command output===========

However ,the output of "ConnectionInfo" property shows as "System.Management.ManagementBaseObject" ,why ?



Add random number to a email id while creating account in active directory

$
0
0

Hi,

I have this code with me,

in this code i am creating user account into the active directory, i am facing issue in validating it.

validation is: Let's say we got 2nd Aman verma into the active directory, first aman verma got id as aman.verma@xyz.com, i want id of second aman verma as aman.verma1@xyz.com (or any other number at the place of 1)

below is my code,

using System;
using System.IO;
using System.DirectoryServices;

namespace ActiveDirectoryAddContacts
{
class Class1
{
static void Main(string[] args)
{
System.DirectoryServices.DirectorySearcher DSESearcher = new System.DirectoryServices.DirectorySearcher();
string RootDSE=DSESearcher.SearchRoot.Path;

RootDSE=RootDSE.Insert(7,"ou=Mytest,");
DirectoryEntry myDE = new DirectoryEntry(RootDSE);
DirectoryEntries myEntries = myDE.Children;
// Create a new entry 'Sample' in the container.

FileStream fs = new FileStream("C:\\UserDetails.csv" , FileMode.OpenOrCreate, FileAccess.Read); 
StreamReader sr = new StreamReader(fs); 
for(int i=1;i<291;i++)
{
string str = sr.ReadLine();
char[] ca={','};

try
{
string[] sa = str.Split(ca,4);
DirectoryEntry myDirectoryEntry = myEntries.Add("CN="+sa[2], "user");
myDirectoryEntry.Properties["givenname"].Value=sa[0];
//myDirectoryEntry.Properties["sn"].Value=sa[1];
//myDirectoryEntry.Properties["displayname"].Value=sa[2];
//myDirectoryEntry.Properties["mail"].Value=sa[3];
//myDirectoryEntry.CommitChanges();
}
catch (Exception e)
{
Console.WriteLine(str);
}
}
}
}
}

 

any Help will be highly appreciated.

Thank you!

Aman 

Powershell ISE: log each command executed with date and time?

$
0
0

Hi,

I'd like to log each Powershell command I log from my Powershell ISE.
Found this: http://jaworskiblog.com/2011/08/05/logging-all-powershell-commands-and-output/ but this does not seem to work from ISE, I get "start-transcript : This host does not support transcription".

Any other suggestion to be able to log each command in powershell with date and time into a logfile?
Please note I'm not at all a guru in Powershell scripting. I'd need just a simple solution.

J.


Jan Hoedt

run script without logon

$
0
0

Hey there,

I have a task and I'm not sure about the feasibility.

I run a windows terminal server farm with roaming profiles and I would write a script which rename a folder on the user fileshare.

The user has \\fileshare\profile\important and I want to rename this folder to \\fileshare\profile\important.backup.

My problem is this is a sync folder. When the user has a session and execute this script - rename works, but when the user do a logoff the important folder would be write back to the fileshare.

And I'm not really sure how to solve this problem. My (abstract) idea is to build a simple batch script on a other fileshare and when the user clicks a button on an application the batch script starts with 120 seconds delay, during this delay the user logoff and after this delay (and no other session) the rename would be happen.

But how is it possible to execute a script (with user permissions) and in the same time a logoff my user session (and have no other session running)

I would be very happy about some ideas for my problem.

Thanks,

Patrick

Menu Example / Powershell

$
0
0

Hello

Does any have or can point me to a simple menu options for powershell.

I want to be able to run various commands and checks on servers via this menu, example ping a server, get logs etc.

I'm still newish to PowerShell, so don't need any thing fancy, just a simple menu from which I can then add to.

Regards

Dee 


Dee

Central Powershell server with central logging?

$
0
0

Hi,

Any way we could have a central Powershell server to which our team can connect (and has all features/modules enabled for Exchange, VMWare etc) + has a central logging per user (which command executed when) so we have tracing + knowledge sharing?

Please advise.
J.


Jan Hoedt

Script to Find latest Modify date, and email alert if last modify is older than 4hrs or so

$
0
0

So, I want to monitor a directory, and get an alert if any file in the directory was not modified in the last, 4 hours or so.  

I think I'm on the right track, but I'm missing some pieces here.  Any suggestions?

Here's what I got so far:

::Set time and date to use later if needed
set currentTime_Date=%time% %date%
::For loop to pull the last file (I can't seem to pull the last modify time/date with it... this is where I need a hand)
FOR /F "delims=" %a IN ('DIR "*.*" /B /O:D') DO SET NewestFile=%a 

::Email latest file using blat
blat.exe -to my@email.com -server server@domain.com -f from@email.com -subject "File Checker" -body "test" -attach %NewestFile%(Not sure if I can use the variable for my newest file here or not)


Any suggestions?



Microsoft Office Key Lookup VBS

$
0
0

So I have this script that I have been working on. The file path is correct and the box and everything else loads but it is not generating the key. I work in IT and we have to format Hard Drives all the time. This means re-installing microsoft office on the PC. Office 2013 has done everything in their power to hide the CD key from you. Belarc and some other software cant find it anymore. I will place the script down below. Not sure why it doesnt work anymore. Any help would be awesome. Ofcoarse you would help everyone else out with this problem. This script makes the key pop up in a little nice neat window when it works. 

Set WshShell = CreateObject("WScript.Shell")
MsgBox ConvertToKey(WshShell.RegRead("HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Office\15.0\ClickToRun\Scenario\INSTALL\ProductKeys"))

Function ConvertToKey(Key)
Const KeyOffset = 52
i = 28
Chars = "BCDFGHJKMPQRTVWXY2346789"
Do
Cur = 0
x = 14
Do
Cur = Cur * 256
Cur = Key(x + KeyOffset) + Cur
Key (x + KeyOffset) = (Cur \ 24) And 255
Cur = Cur Mod 24
x = x -1
Loop While x >= 0
i = i -1
KeyOutput = Mid(Chars, Cur + 1, 1) & KeyOutput
If (((29 - i) Mod 6) = 0) And (i <> -1) Then
i = i -1
KeyOutput = "-" & KeyOutput
End If
Loop While i >= 0
ConvertToKey = KeyOutput
End Function



export attribute with thumbnailphoto

$
0
0

What  is the  syntax  command  to export the  users  without thumbnail photo attribute .

I Just want to have a list users without picture .

Thanks


IT

Script to merge multiple CSV files together with no duplicate records.

$
0
0

I like a Script to merge multiple CSV files together with no duplicate records.

None of the files have any headers and column A got a unique ID. What would be the best way to accomplish that? 

Combine a select-object for both an field, and a hashtable.

$
0
0

Hi....I've got the following PSCustom Object that is returned from an API.  This is returned in a variable called $BPOrder.response 

id                   : 60
parentOrderId        : 0
shippingStatusCode   : ASS
placedOn             : 2015-03-04T09:54:38.000-05:00
createdOn            : 2015-03-04T09:55:26.000-05:00
createdById          : 1627
priceListId          : 2
delivery             : @{shippingMethodId=0}
currency             : @{accountingCurrencyCode=USD; orderCurrencyCode=USD; exchangeRate=1.000000}
totalValue           : @{net=72.80; taxAmount=0.00; baseNet=72.80; baseTaxAmount=0.00; baseTotal=72.80; total=72.80}
assignment           : @{current=}
parties              : @{customer=; delivery=; billing=}

I can return a list of the order IDs by 

PS>$BPOrders.response | select-object ID 

id
--
11
12
13
14

etc.

The parties, above is a hash table of hash tables.  and I would think I could return the contents of those using dot notation but i doesn't appear to work.  

$BPOrders.response | select parties.delivery.addressFullname,  parties.delivery.addressCity  etc. etc. 

What I need is the delivery address of the customer coupled with the ID of the of the order.  Something like: 

$BPOrders.response | select id, parties.deliery.addressFullname, parties.delivery.addressCity 

Ideas of how to do this?   

I can get at the address and them by looping through each using the following statement: 

#$BPOrders.response | foreach-object ($_) { `
     (Out-String -InputObject $_.id)+`
     (Out-String -InputObject $_.parties.delivery.addressFullName)+`
     (Out-String -InputObject $_.parties.delivery.addresscompanyname)+`
     (Out-String -InputObject $_.parties.delivery.addressLine1)+`
     (Out-String -InputObject $_.parties.delivery.addressLine2)+`
     (Out-String -InputObject $_.parties.delivery.addressLine3)+`
     (Out-String -InputObject $_.parties.delivery.addressLine4)+`
     (Out-String -InputObject $_.parties.delivery.postalcode)
     
     }

This gives me just the data..... I'd really like to have the name pairs as well because I want to ulimately put these in a csv 

60 <--ID 
nichole steffens <--addressFullName
PO 58 <--addressline1
Saxeville <--addressline2 
Wisconsin
54976

Here's what I want: 

ID: 60
addressFullName: nichole steffens
addressLine1: PO 58 

etc. etc. 

  

 

arp -a

$
0
0

This is a follow-up of my previous post, where I was asking if there is a cmdlet like "arp -a" in PowerShell which could provide an object as an output and not simply text.

The answer was very useful and it worked. But the static method Get() cannot be used without specifyng a target, single IP address. If I correctly understood the source code in the linked post, the method Get() looks for the system ARP table, so it will anyway provide multiple outputs.

But what if I wanted to run Get() for a single, known IP?

Or: is there another (built-in or custom) cmdlet which can run a command like "arp -a <ip_address>" and return an object?

Run with user privileges but write to restricted folder

$
0
0

In Windows Server 2008 R2 (and in an Active Directory domain), the login and logoff scripts are run with user privileges.

Suppose that I run script1.ps1, when user1 logs in; I need that script1.ps1 is associated to user1, because it will write some informations about that user: it modifies a log file in a folder. Anyway, script1.ps1 will be run with user1 privileges.

I obviously made that file and that folder accessible (readable/writable) to user1: but I actually don't want the user to modify that log file. I would like thatonly the script could do it.

Is there a way to work around this problem? Maybe should I run script1.ps1 in a different way?


Group Policy Startup Script Applies My Policy But Does Not Run The Acual Scripts

$
0
0

I have created a basic batch file with msiexec.exe to uninstall a program on startup and then another separate .bat script to install the same program but the newer version. The software I'm referring to has to be completely uninstalled BEFORE I install the "newer" version of the same program, it cannot just be overwritten. If I run a gpupdate /force on the client computer and restart, the scripts run as they are supposed to and everything works but the problem is that I can't get it to run on first boot on a computer that has been turned off for months, even after multiple reboots it still doesn't run the scripts. The 3 policies apply to the different computers/users but the scripts don't run. I manage a theme park that is only open 4 months of the year so the rest of the time the in park PC's are turned off. I have created my OU as "POS Computers & Users" which has all of the computers and users that will take this policy. I also have 3 Group Policy Objects attached to this OU in Group Policy, 1 is the program uninstallation .bat script policy that runs on startup, 2 is the install .bat script policy that runs after the uninstallation script, and 3 is the Default Policy for the OU. I already have the"Always wait for the network at computer startup and logon", "Run startup scripts visible"enabled, "Run startup scripts asynchronously" disabled, and "Run Logon Scripts Synchronously" enabled for all 3 of the policies. They are all "link enabled" and security filtering is set to only the OU I mentioned earlier so that it doesn't affect anyone else. I have the link order set as the script I want to run first as the last and the one I want to run last first because from what I understand inheritance is from bottom to top. The install file is accessible by everyone with full permissions on our "Shared" drive so I know its not a permissions issue because it runs after a gpupdate /force with a restart. The scripts are in the proper folder for the policies they are attached to and permissions are fine.

Here is my uninstall .bat script (msiexec.exe /X{14324A6A-BDD1-4F40-8E77-664C8AEEA251} /forcerestart /qb-! ALLUSERS=1 REMOVE=ALL)

Here is my install .bat script (msiexec.exe /i {\\kksrvad\shared\Gatemaster\NewGatemaster.msi} /qb ALLUSERS=1)


I need a script to help me check all the AD Computers for a certain file.

$
0
0

What I'm looking for is a script that I can use to check all the AD computers in my domain for a file that was created by Malware. It would be great if the script could export the results as a csv and have a column for the computer name, IP address, and if the file/path exists.

I'm new to Powershell and I've been trying to script it on my own but no luck so far. I would be extremely great-full for any help, or a point in the right direction.

I messed around with different commands:

I'm not sure if I should be using test-path or get-childitem with recursive and wildcards.

This is a sample of what I'm working with... I know it probably horrible but like I said I'm new.

$date = [DateTime]::Today.AddDays(-90)
$AllComps = get-adcomputer -filter {(Enabled -eq 'true') -and (lastlogondate -gt $date)} | select name
$Allcomps = $AllComps[100..125]

foreach ($ADcomputer in $AllComps)
{
function check-remotefile {
 
    PROCESS {
 
                $file = "\\$_\C$\Windows\notepad.exe"
 
                if (test-path $file)
 
                {
 
                echo "$ADcomputer: .exe exists"
 
                }
 
            }
 
        }
}

I get sysem offline error in below script for scanning open ports on remote computer,

$
0
0

SCRIPT: Output is "System offline" even computer is on.  

strInputFile = "C:\Monthly Activity\2015\Port scan\Port qry on remote\computers.txt"

' Make the log file accessible via UNC to the account running the script
strLogFile = "C:\Monthly Activity\2015\Port scan\Port qry on remote\netstatresults.csv"
' Specify the path to PSExec
strPSExec = "C:\Monthly Activity\2015\Port scan\Port qry on remote\psexec.exe"
' Specify the list of ports to search netstat output for


Set objShell = CreateObject("WScript.Shell")
Set objFSO = CreateObject("Scripting.FileSystemObject")
Const intForReading = 1

strPSExec = objFSO.GetFile(strPSExec).ShortPath

WriteLog strLogFile, String(80, "=") & vbCrLf & "Script started " & Now & vbCrLf & String(80, "=")
Set objInputFile = objFSO.OpenTextFile(strInputFile, intForReading, False)
WhileNot objInputFile.AtEndOfStream
    strComputer = objInputFile.ReadLine
    If Ping(strComputer) = TrueThen
        WriteLog strLogFile, vbCrLf & "Scanning computer " & strComputer
            strCommand = "cmd /c " & strPSExec & " -accepteula \\" & strComputer & "cmd /c" & "netstat -a" & "> """ & strLogFile & """"
            objShell.Run strCommand, 0, True
        'Next
    Else
        WriteLog strLogFile, vbCrLf & strComputer & " is offline"
    EndIf
Wend
objInputFile.Close 

WriteLog strLogFile, vbCrLf & "Script finished " & Now & vbCrLf
WScript.Echo vbCrLf & "Done. Please see " & strLogFile

Function Ping(strComputer)
    Dim objShell, boolCode
    Set objShell = CreateObject("WScript.Shell")
    boolCode = objShell.Run("Ping -n 1 -w 300 " & strComputer, 0, True)
    If boolCode = 0Then
        Ping = True
    Else
        Ping = False
    EndIf
EndFunction

Sub WriteLog(strFileToWriteTo, strMessage)
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    Set objOutput = objFSO.OpenTextFile(strFileToWriteTo, 8, True)
    objOutput.WriteLine strMessage
    objOutput.Close
    Set objOutput = Nothing
EndSub


prakash

PS v2 + custom objects + multiple values + export-csv

$
0
0

I have a script that gets a list of patches from WSUS and exports a subset of their attributes to a .csv file by creating a custom object. When I run the script and have the output sent to the host, I see the KB field looks like this: {KB123456}, which is fine. When I run the script and use "Export-Csv", the KB column says, "System.Collections.Specialized.StringCollection".

What do I need to change, in the code, to get the actual value(s) of the StringCollection into my CSV? I've seen the Join function, but haven't been able to make it work.

Thanks.

$PrimaryWSUSServer = 'wsus.company.local'

Function Get-PatchesPendingApproval {
    $updateScope = New-Object Microsoft.UpdateServices.Administration.UpdateScope
    $updatescope.FromArrivalDate = (Get-Date).AddMonths(-2)
    $updatescope.ApprovedStates = [Microsoft.UpdateServices.Administration.ApprovedStates]::NotApproved
    $needApproval = $wsus.GetUpdates($updateScope)
    Return $needApproval
}

#Begin Script
[void][reflection.assembly]::LoadWithPartialName(“Microsoft.UpdateServices.Administration”)
$wsus = [Microsoft.UpdateServices.Administration.AdminProxy]::getUpdateServer($PrimaryWSUSServer,$False)

$updatesToApprove = Get-PatchesPendingApproval

Foreach ($item in $updatesToApprove) {
    $updateProps=@{
        'Title'=$item.Title
        'KB'=$item.KnowledgebaseArticles
        'ApprovalDate'=Get-Date
        'ArrivalDate'=$item.ArrivalDate
    }

    New-Object PsObject -Property $updateProps
}


VBScript to run commands

$
0
0

Hello ,

I am using third application called Streamserve , there is one customized command of Streamserve which can be run from command prompt in following way ,

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

C:\Users\Mukund Sawant\Desktop\VBScript>C:\Program Files\OpenText\StreamServe\Platform\Core\1.5.\bin\ss_scm.exe -user Administrator -pass XYZ -cert "C:\ManagementGateway\CERT.crt" -servicename app1 -action stop

Above command can be run manually from command successfully . I want to run this command from vbscript and for that I have used the following lines of code ,

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

command = "C:\\Program Files\\OpenText\\StreamServe\\Platform\\Core\\1.5.2\\bin\\ss_scm.exe -user " + userid + " -pass " + passwd + " -cert " + cert + " -servicename " + strs_svc + " -action stop"        
    set WshShell = CreateObject("wscript.shell")
    'set ReturnCode =
 WshShell.Run command , 0, true

I also tried below scenario which doesn't generate any error but it doesn't fire the command in background ,

WScript.Echo "Application "  & er & " will be stopped "
command = "cmd /c C:\Program Files\OpenText\StreamServe\Platform\Core\1.5.2\bin\ss_scm.exe -user " + userid + " -pass " + passwd + " -cert " + cert + " -servicename " + strs_svc + " -action stop"        
    set WshShell = CreateObject("wscript.shell")
    'set ReturnCode =
 WshShell.Run command , 0, true

I would like to know the way of running any third party application's  command in non-interactive way form cmd and it should also generate a log.

Thank you in advance.

Regards,

Mukund

Powershell to SQL

$
0
0

Hi!

Import-Module "SQLPS" -DisableNameChecking

$SQLserver = "Oracle11" #Read-Host "Hva er navnet på SQL-serveren?"
$SQLdbname = "test" #Read-Host "Hva er navnet på databasen du skal opprette?"
$Database = New-Object Microsoft.SqlServer.Management.Smo.Database($SQLserver, $SQLdbname)
$release = "E:\EQS-release" #Read-Host "hvor ligger releasemappen?"
$version = "eqs-3_14_0_7"
$dbusername = "eqsdba" #Read-Host "hvilket brukernavn skal brukeren ha?"
$dbpassord = "<password>" #Read-Host "hva er passordet til brukeren?"

$connectionString = "Server=$SQLserver;uid=$dbusername; pwd=$dbpassord;Database=$SQLdbname;"
$connection = New-Object System.Data.SqlClient.SqlConnection
$connection.ConnectionString = $connectionString

$connection.Open()

$sqlpath = "$release\$version\eqs\config\install\sql\"
$sqlpathlong = "$release\$version\$version\eqs\config\install\sql\"

if (Test-Path $sqlpath) {
    cd $sqlpath
    Invoke-SqlCmd -ServerInstance $SQLserver -Database $database -Username $dbusername -Password $dbpassord -InputFile "mssql_create_clean_db.sql"
    Invoke-SqlCmd -ServerInstance $SQLserver -Database $database -Username $dbusername -Password $dbpassord -InputFile "mssql_create_clean_db_LANG.sql"
    Invoke-SqlCmd -ServerInstance $SQLserver -Database $database -Username $dbusername -Password $dbpassord -InputFile "mssql_index.sql"
} else {
    cd $sqlpathlong
    Invoke-SqlCmd -ServerInstance $SQLserver -Database $database -Username $dbusername -Password $dbpassord -InputFile "mssql_create_clean_db.sql"
    Invoke-SqlCmd -ServerInstance $SQLserver -Database $database -Username $dbusername -Password $dbpassord -InputFile "mssql_create_clean_db_LANG.sql"
    Invoke-SqlCmd -ServerInstance $SQLserver -Database $database -Username $dbusername -Password $dbpassord -InputFile "mssql_index.sql"
}

I'm trying to run the code above, but when i come down to the invoke-sqlcmd, i get this error:

PS E:\EQS-release\eqs-3_14_0_7\eqs\config\install\sql> C:\Users\Administrator\Desktop\sqtestl.ps1
Invoke-SqlCmd : Could not load file or assembly 'Microsoft.SqlServer.BatchParser, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91' or one of its dependencies. The system c
annot find the file specified.
At C:\Users\Administrator\Desktop\sqtestl.ps1:22 char:5
+     Invoke-SqlCmd -InputFile "mssql_create_clean_db.sql" | Out-File -filePath "E ...
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Invoke-Sqlcmd], FileNotFoundException
    + FullyQualifiedErrorId : System.IO.FileNotFoundException,Microsoft.SqlServer.Management.PowerShell.GetScriptCommand
 

In the C:\assembly i can se that Microsoft.SqlServer.BatchParser is in version 10.0.0.0.

I've downloaded:

SQLSysClrTypes.msi and SharedManagementObjects.msi both 64bit

Is there anything im missing?

Viewing all 15028 articles
Browse latest View live


Latest Images

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