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

Update Excel file from 2nd Excel File

$
0
0

Hi.

I am looking to write a batch job that looks at the values in a specific column in an excel file (or csv file) and finds that same value in a 2nd excel or csv file.  When it finds it, it adds a new value in a new column in that row with the value in the corresponding row of the file where the value was found.

Any suggestions?
Thank you!!


hOW Copy File to another folder

$
0
0

Hi. I am new to vbscript and trying to learn to create script from scratch. I am trying to copy a file from one folder to another that has date equal to what I specify:

dim myfile, copymyfile, myfile2
set objfso=CreateObject("Scripting.FileSystemObject")
targetfolder="C:\Users\Documents\820\accounts"
targetdate="03/06/2016"
set objfolder=objfso.getfolder(targetfolder)
set colfiles=objfolder.files
for each element in colfiles
If formatdatetime(element.DateLastModified,vbShortdate) = targetdate then
myfile=element.name&vbTab&formatdatetime(element.DateLastModified,vbShortdate)
myfile2=element.name
wscript.echo myfile
wscript.echo myfile2
' How do I copy file in myfile2 to another folder?
Else
'WScript.Echo "sorry"
End if
next

Thank you in advance for your time and help/

Batch File Not Working

$
0
0

Hello,

I had created a batch file which :

1) Creates a folder under C: drive
2) Copies data over the network to this created folder
3) Creates new environment variable

The script is segregated for x86 and x64 systems based on below :

....................................................................................................................................................................

:CheckOS
IF "%PROCESSOR_ARCHITECTURE%"=="x86" (GOTO 32BIT) ELSE (GOTO 64BIT)

:32BIT
md C:\TEST\x86
xcopy /s "\\Servername\Foldername\x86" "C:\TEST\x86"
setx TEST_HOME C:\TEST\x86
GOTO END

:64BIT
md C:\TEST\x64
xcopy /s "\\Servername\Foldername\x64" "C:\TEST\x64"
setx TEST_HOME C:\TEST\x64
GOTO END

:END

....................................................................................................................................................................

The script was working fine but suddenly it has started behaving strangely. It is only executing first two lines of the 32BIT  category for both x86 or x64 systems and doesnt do anything else, which it was doing some time back. Once this works, my main motive is to achieve the following script. This is what I was trying to achieve and modified the script and it now doesnt work for the first scenario which it was :

:CheckOS
IF "%PROCESSOR_ARCHITECTURE%"=="x86" (GOTO 32BIT) ELSE (GOTO 64BIT)

:32BIT
md C:\TEST\x86
xcopy /s "\\Servername\Foldername\x86" "C:\TEST\x86"
setx TEST_HOME C:\TEST\x86
GOTO END

:64BIT
md C:\TEST\x86

md C:\TEST\x64
xcopy /s "\\Servername\Foldername\x86" "C:\TEST\x86"
xcopy /s "\\Servername\Foldername\x64" "C:\TEST\x64"
setx TEST_HOME C:\TEST\x86
setx TEST_HOME C:\TEST\x64
GOTO END


:END

I am trying to achieve this via SCCM. The above (2nd script) works when executed from command prompt on the local system.

vbscript which will remove all characters before "\" from string

$
0
0

I am looking for a vbscript which will remove all characters before "\" from string...

for e.g. Input as below -


abcdefg\First

jhgtrf\Second

qertt55\Third

pqwes\Four

word\1234567

 

output should be like this-

First

Second

Third

Four

1234567


Can someone guide me?


Thanks & Best Regards, MPG

Invalid Enumeration Context using powershell script to check computer accounts

$
0
0

Hello,

I am using a powershell script downloaded from technet gallery (http://gallery.technet.microsoft.com/PowerShell-Organize-d37c2a29#content) to automatically move the computers to OUs based on IP subnets in active directory. But after a while the script is failing with an error 'Invalid Enumeration Context'  on the line

Get-ADComputer -Filter { OperatingSystem-like "Windows 7*" -or OperatingSystem -like "Windows XP*" }-Properties PasswordLastSet |ForEach-Object {

I tried to fix the error by including diffrent Page Size values 10, 1 and 0 as shown below but thats only helped to run the script a little longer before failing with the same error. I also incrased the MaxPageSize value to 10000 in ladp policies using ntdsutil in active directory but had no effect.

Get-ADComputer -Filter { OperatingSystem-like "Windows 7*" -or OperatingSystem -like "Windows XP*" }-Properties PasswordLastSet -ResultPageSize 1 |ForEach-Object {

Can you please help me with this issue?

Thanks veru much in advance!

Jashy

create new user user mail box using power shell script

$
0
0

hi ,the following is the script to create new user mail box in office 365 trail

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

  • Shell command:

$secpasswd=ConvertTo-SecureString "${AdminPassword}" -AsPlainText -Force;

                    $mycreds=New-Object System.Management.Automation.PSCredential("${AdminUserId}",$secpasswd);

                    $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri 
https://ps.outlook.com/powershell/  -Credential $mycreds -Authentication Basic -AllowRedirection -WarningAction SilentlyContinue;

                    Import-PSSession $Session -CommandName Remove-mailbox, Get-mailbox, New-Mailbox -AllowClobber -DisableNameChecking -WarningAction SilentlyContinue | Out-Null;

                    get-mailbox '${Name}' | select-object name | out-null;

                    if($? -eq "True")

                    {remove-PSSession $Session; Write-Host "This mailbox already exist"; exit 1;}

                    else

                    {

                    get-mailbox '${UserPrincipalName}' | select-object name | out-null;

                    if($? -eq "True")

                    {remove-PSSession $Session;Write-Host "This mailbox already exist"; exit 1;} else { New-Mailbox -Alias '${Alias}' -Name '${Name}' -FirstName '${FirstName}' -LastName '${LastName}' -DisplayName '${DisplayName}' -MicrosoftOnlineServicesID '${UserPrincipalName}' -Password (ConvertTo-SecureString -String '${UserPassword}' -AsPlainText -Force) -ResetPasswordOnNextLogon $false -WarningAction SilentlyContinue | out-null;

                    if($? -eq "True") {remove-PSSession $Session; exit 0;} else {remove-PSSession $Session; write-host "Mailbox could not be created. Check for password or UserPrincipalName."; exit 1;}

                    }

                    }

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

  • The error which i am getting is :

Failed

 

Cause:

New-PSSession :

At line:3 char:17

+ $Session = New-PSSession -ConfigurationName

Microsoft.Exchange -ConnectionU ...

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

~~~~~~~~~~~~~~~~~~

  + CategoryInfo : InvalidArgument: (
https://ps.outlook.com/powershell/:Uri) [New-PSSession], PSInvalidOperationException

  + FullyQualifiedErrorId : CreateRemoteRunspace,Microsoft.PowerShell.

  Commands.NewPSSessionCommand

 

Import-PSSession : Cannot validate argument on parameter 'Session'. The

argument is null. Supply a non-null argument and try the command again.

At line:4 char:23

+ Import-PSSession $Session -CommandName Remove-mailbox,

Get-mailbox, New-Mai ...

+ ~~~~~~~~

  + CategoryInfo : InvalidData: (:) [Import-PSSession], ParameterBi

  ndingValidationException

  + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.Power

  Shell.Commands.ImportPSSessionCommand

 

get-mailbox : The term 'get-mailbox' is not recognized as the name of a

cmdlet, function, script file, or operable program. Check the spelling of the

name, or if a path was included, verify that the path is correct and try again.

At line:5 char:6

+ get-mailbox 'vinod' | select-object name | out-null;

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

  + CategoryInfo : ObjectNotFound: (get-mailbox:String) [], Command

  NotFoundException

  + FullyQualifiedErrorId : CommandNotFoundException

 

get-mailbox : The term 'get-mailbox' is not recognized as the name of a

cmdlet, function, script file, or operable program. Check the spelling of the

name, or if a path was included, verify that the path is correct and try again.

At line:10 char:6

+ get-mailbox 'vinod@pesit.onmicrosoft.com' |

select-object name | out-null;

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

  + CategoryInfo : ObjectNotFound: (get-mailbox:String) [], Command

  NotFoundException

  + FullyQualifiedErrorId : CommandNotFoundException

 

New-Mailbox : The term 'New-Mailbox' is not recognized as the name of a

cmdlet, function, script file, or operable program. Check the spelling of the

name, or if a path was included, verify that the path is correct and try again.

At line:12 char:90

+ ... xit 1;} else { New-Mailbox -Alias 'vinod' -Name 'vinod' -FirstName

'vinod' -Last ...

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

  + CategoryInfo : ObjectNotFound: (New-Mailbox:String) [], Command

  NotFoundException

  + FullyQualifiedErrorId : CommandNotFoundException

 

Remove-PSSession : Cannot validate argument on parameter 'Id'. The argument is

null. Supply a non-null argument and try the command again.

At line:13 char:84

+ ... move-PSSession $Session; write-host "Mailbox could not be created. Check

for pas ...

+ ~~~~~~~~

  + CategoryInfo : InvalidData: (:) [Remove-PSSession], ParameterBi

  ndingValidationException

  + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.Power

  Shell.Commands.RemovePSSessionCommand

 

Mailbox could not be created. Check for password or UserPrincipalName.

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

  • pre requisites which i am using is:

- Microsoft Online Services Sign-in Assistant

- Windows Azure Active Directory Module

-Windows Management Framework 3.0

-SharePoint Online Management Shell

-SSH Server (Version 3.0)

-Set-ExecutionPolicy Unrestricted

Please help

Using validateset with parameter which contains embedded spaces.

$
0
0

param([parameter(Mandatory=$true)][ValidateSet("abc",'"abc def"')

it fails in the second argument.....


michael john ocasio


How do I use PowerShell to connect to a vpn (Cisco AnyConnect) from my home Windows 7 computer?

$
0
0
I have a Windows 7 computer that I use to remote in to my workstation computer via the vpn (Cisco AnyConnect). I wanted to know if there is a PowerShell script that will make the automate the process instead of waiting for the UI to load?

User account audit for application that is not AD aware

$
0
0

I'm learning PowerShell and have become stumped.

My company has an application that is not AD aware, but has it's own directory of users.  We enforce the same naming standards in that application as we do in AD.  This means I can export the names of the application users to a CSV and have what equates to a list of SamAccountNames in AD.  The task I have is to audit that list of user names against AD to find application users that are no longer in the company and clean them out. The other trick is the list of users could be in any of the 4 child domains in our company.

Ideally, I would like the row in the CSV deleted so there are no null values in the CSV making it possible to use the application's scripting to remove the users in the CSV.  Another option is to export a new CSV with only the usernames that are not found in AD. This is going to become a routine task I would like to fully automate.  If the only option is the null the value, I don't mind going in and editing out the empty rows manually.

Here is my code so far...

$domains=Get-ADForest|Select-Object-ExpandPropertyDomains|Sort-ObjectDomains

Foreach ($domainin$domains){

Import-Csv C:\Users.csv|ForEach-Object{

$User = Get-ADUser -Identity$_.User

If ($User-eq$Null) {}  (Trying to tell it to do nothing)

Else  ????????? ($User -ne $Null)delete the row from the csv

}

Script for finding out the UNC paths of a users mapped drives

$
0
0

Hi!

Hopefully someone here can help me with this. Sorry if this is the incorrect forum! :)

Using "net use" in CMD gets me all the UNC paths for the mapped drives on my PC - Great! 

However...

Do you know of any way to do the same to find out the UNC paths for mapped drives of a network user?

For example if I wanted to know what the UNC paths are for your mapped drives and were both on the same network, are you aware of a CMD command that will give me that? I've been researching it but I have come up with zip!

Thanks for your help!

Delete multiple computer objects from Active Directory

$
0
0
Need script which can pick the list of the computer objects from a text file and delete them from an Active Directory

Enabling Bitlocker via script

$
0
0

Hi, guys!

I'm trying enable bitlocker on my non-tpm PCs

I've add policy which allows use password only for bitlocker

I'm trying this cmdlet:

Enable-BitLocker -MountPoint C: -PasswordProtector -Confirm -EncryptionMethod Aes128 -Password ("12345678" | ConvertTo-SecureString -AsPlainText -Force) -SkipHardwareTest -UsedSpaceOnly

But I catch the error: Enable-BitLockerInternal : Value does not fall within the expected range.

How can I fix it?

Unable to assign default value to parameter for cmdletbinding

$
0
0

Hi Everyone

I'm trying to assign a default value of "All" to my parameter $TenantName in below script:

#Function for getting tenant sites
function Get-SPTenantSites()
{
   [CmdletBinding()]
    Param(
         [parameter]
         [alias("TenantAlias","Identity")]
         [string]
         $TenantName = "All"
    )

    $WebApplication = Get-SPWebApplication $hostingMainURL
    $Sites = $WebApplication.Sites

    Write-Host "SP sites  for $TenantName tenant in this farm are: "
    if($TenantName -eq "All")
    {
        #do something
    }
    else
    {
       #do something else
    }

}

When I run this function:

Get-SPTenantSites 

I get below error:

Get-SPTenantSites
Get-SPTenantSites : Cannot process argument transformation on parameter 'TenantName'. Cannot convert the "" value of type "System.String" to type "System.Management.Automation.ParameterAttribute".

Pls advise what is wrong here.


Thanks
Mohit

Come up with a Startdate in the week and a end Date in the Week

$
0
0

I am trying to create two variables that will be passed to a command that needs a start date and an end date.

THis is to gather date for transaction logs that are kept for 30 days.  So I figure that I need to run the script twice a month.  Once to grab the first two weeks of the month we are in.  And a second one that will grab the last two weeks of the month prior.  THe dates cannot include weekends.

So for instance 1st of May is a Sunday so I need the start date to be 2nd of May and then enumerate the end date to be the friday after that.

With a second start date to be the following Monday and end date the following friday.

I tried a few things like this.

These get me the Month prior and the first day of that Month.

$LASTDAYOFMONTH = ((Get-Date | ForEach-Object {Get-Date -Date ([datetime]"$($_.Month) 1, $($_.Year)")}).AddMilliseconds(-1))

$FIRSTDAYOFMONTH=GET-DATE $LASTDAYOFMONTH -Day 1

and then this function

Function Get-FirstDay($day) {

 

While ($day.dayofweek -eq "Sunday" -or $day.dayofweek -eq "Saturday"){

Write-Host $Day

$Day = $day.AddDays(1)

}

Return $day

}

$StartDay = Get-FirstDay $FIRSTDAYOFMONTH

The problem is within the function it is not seeing the day of week for the format.  I am not sure if I am going about it right.



Jeff C

VBscript to do a recursive search for multiple files with different names and output their path to a text file

$
0
0
Ok so I need to search multiple computers for certain files that may indicate an infection. I want to use a vbscript that I can just drop in the C:\ folder and let it run and it creates a text file for the out put. I have 13 different file names to look for. I've looked around for vbscripts that do this, but all I can find are ones for just one specific file, or for a certain file time. I can't find a recursive search for multiple specific files. Any help would be appreciated.

icacls remote against %temp% folder

$
0
0

Hi

I have a bat file that is copied to users profile temp directory which I remotely execute to gather support diagnostic info

On some machines it does not launch. I remoted onto same machine and tried to launch manually from the temp folder but still would not launch and i seen error "Windows cannot access the specified device, path, or file. You may not have appropriate permissions to access the item."

I copied the bat to the user desktop and it ran just fine.

Its the same antivirus on each machine and I cant see why it would work on some and not others.

There are no restrictions on running bat files

It seems to not want to run from the users c:\users\%username%\appdata\local\temp directory.

I researched that there is some glitch with the temp folder where we need to click |security| > advanced   > " [  ] include inheritable permissions from this objects parent"    to get the user permissions to run programs from their temp folder.    Doing this from the GUI on each machine however is not an option.

I want to use icacls remotely against the users machine to apply that setting, truth be told i got confused and want to make sure this is done right, want to give the logged on user full rights on their temp file and check the setting to include inheritable permissions.

I'm thinking below is correct but I cant find the exact example i need and want to make sure it covers all that

icacls.exe  \\server1\c$\users\user1\appdata\local\temp /Grant "domain1\user1":(OI)(CI)F

Let me know

Thanks for reading


confuseis


Getting More Information with Get-ChildItem

$
0
0

How do I get the following command

Get-ChildItem -Path "path" | Select-Object -Property p1,p2,p3,p4

to have an output format similar to Get-ChildItem -Path "path"

ForEach loop does not work

$
0
0

Hello,

I am starting with PS. As a test I want to rename folders. I put the foldernames in an array.

$DirectoryNames="C:\FotoAlbum","C:\FotoAlbum-Poort5","Testfolder"
cls
ForEach($DirectoryName in $DirectoryNames)
{
 $DirectoryName
 Get-ChildItem $DirectoryName -Directory -Recurse | Where-Object { $_.name -like "* *"} | Rename-Item -NewName { $_.name -replace ' ', '-'} -Verbose
}

The spaces are not replaced by a minus sign in the folders. The foldername is shown during while running the script.

Any help is appreciated and with kind regards,

Willem-Jan

turn off computers with a script

$
0
0

when I try to shut down multiple computers and attempt to load the ip of the computers in a txt it does not work. I tried two ways and fails. I need to turn off 40 pcs, it is difficult to write all these ips.

first form

(get-wmiobject -class win32_operatingsystem -computername (invoke-command { get-content C:\Users\Eventos\Documents\ip.txt } -computername \\N00019396)).win32shutdown(6)

second form

(get-wmiobject -class win32_operatingsystem -computername (Get-Content \\N00019396\Users\Eventos\Documents\ip.txt)).win32shutdown(6)

PS: get-rdslogonsatus => 'You cannot call a method on a null-valued expression'

$
0
0
Hi,

I'm calling a function in a script
foreach $(computer in $computers){
$LogonStatus = Get-RDSLogonStatus -ComputerName $ComputerName
}

This is the script:
function Get-RDSLogonStatus
{
  param([Parameter(Mandatory = $true)][string]
    $ComputerName
    
   )
   
  $ErrorActionPreference = 'Stop'
  try
  {
    invoke-command -ScriptBlock { chglogon.exe /query } -ComputerName $ComputerName
  }
  catch
  {

    $message = $Error[0].Exception
     
    If ($message.ToString() -like '*logins are currently ENABLED*'){
      $UserLogOnStatus = 'Enabled'    
    }
    Else {$UserLogOnStatus = 'Disabled'}
    
    [PSCustomObject] @{
      LogonStatus = $UserLogonStatus
    }
    

  }
  $ErrorActionPreference = 'SilentlyContinue'
}

It works fine but not always. Sometimes I get:
Get-RDSLogonStatus : You cannot call a method on a null-valued expression.
At C:\Scripts\LogonStatus.ps1

There might be a better way to get the logonstatus but didn't found one (yet).

Please advise.
J.

Jan Hoedt

Viewing all 15028 articles
Browse latest View live


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