Quantcast
Channel: Windows PowerShell Forum
Viewing all 2562 articles
Browse latest View live

Weird Powshell Behavior with Invoke-SQLCMD

$
0
0

So I have some weird behavior going on and was wondering if someone might be able to explain it to me. In the following code I declare $dt as an array and the code works.

$datetime=Get-Date -format "MM-dd-yyyy"
$SQLFilePath="\long_running_query_powershell_.sql" 


$dt=@()

foreach($key in $DBhash.keys){
$Servervalue=$dbhash.item($key)

$qDataRow=Invoke-Sqlcmd -ServerInstance $Servervalue -Database $key -InputFile $SQLFilePath

#Check if data row has data to avoid trying to add properties to a null row
if ($qDataRow -ne $null)
  {
    #Add the SQL server as a property to the data row
    $qDataRow | Add-Member -memberType noteProperty -name Server -value $Servervalue
    #Add the database as a property to the data row
    $qDataRow | Add-Member -memberType noteProperty -name Database -value $key
    $qDataRow | Add-Member -memberType noteProperty -name dtadded -value $datetime
  }
  
  $dt+=$qDataRow
}#End For Loop

However if i do not decare the $dt=@() I get the following error:

Method invocation failed because [System.Data.DataRow] doesn't contain a method named 'op_Addition'.

I copied this code directly from another script that works fine. Below is the SQL query in case that helps:

select aa.Action ActionType, 
		ar.ID,
		ar.ArtifactID,
		ar.Details,
		ar.UserID,
		ar.TimeStamp,
		ar.RequestOrigination,
		ar.RecordOrigination,
		ar.ExecutionTime	

 from EDDSDBO.AuditRecord ar (nolock)
 
 INNER JOIN EDDSDBO.AuditAction AA ON 
 
 AR.Action= AA.AuditActionID
 WHERE [TimeStamp] BETWEEN (select GETDATE () -1) and GETDATE() and  
 ar.Action in (28,29,32,33,34,35,36,37,4,5,6) and ExecutionTime > 10000

 ORDER BY [TimeStamp] DESC 

I am just wondering if I am missing something. I have had 3 other people look at it and they cannot seem to figure out the difference either.


Call Remote Invoke-Command and Not Wait?

$
0
0

Good afternoon-

I have a script that calls the following command:

Invoke-Command -ComputerName $strRemoteServerFQDN -FilePath $strRemotePSCommand -ArgumentList $strJobName

Please excuse me if I don't fully understand how Invoke-Command works, but my question is this: Can I call Invoke-Command in such a way that will cause it to run the command on the remote computer and not wait for the script to complete? Ideally, I'd like SERVER1 (the calling server) to start the command on SERVER2 (the remote server) and not wait for the results, but rather have its script finish regardless of what happens on SERVER2 (I'll handle that separately).

Thank you!
Brian

Insert a value from CSV into a string

$
0
0

Hi All,

I am fairly new to powershell so this maybe an easy answer! I have small Exchange hosting server here and am writing a script to allow my engineers to easily create customer on this server. This part of the script is responsible for creating the user accounts in the correct OU and assigning address books in exchange:

Import-csv "C:\Share\TenantSetup\UserList.csv" | foreach {new-mailbox -name $_.Fullname -alias $_.Alias -userPrincipalName “$_.Alias@internaldomain.local” –FirstName $_.Firstname –Initials $_.Initial –LastName $_.Surname –OrganizationalUnit "internaldomain.local/tenants/$pd” -SamAccountName $_.Alias –AddressBookPolicy “$pd ABP” -Password $password -ResetPasswordOnNextLogon $false}

The account names are pulled from a CSV file, the whole script works with one exception:

-userPrincipalName “$_.Alias@internaldomain.local”

I would expect this to insert the Alias part of my CSV file into the username field however it inserts the whole line of the CSV file. Why would this be? I assume its because its inside a string?

Any help would be much appreciated!

Thanks

Dave

Changed Password now add to domain script not working....

$
0
0

$credential = New-Object System.Management.Automation.PsCredential("company.com\username", (ConvertTo-SecureString "password" -AsPlainText -Force))

$credential = New-Object System.Management.Automation.PsCredential("company.com\username", (ConvertTo-SecureString "$amp@le" -AsPlainText -Force))

I guess I need a little help with the syntax on this one.  I changed my password to something that contained a $ sign and @ symbol and now the scripted won't run.  I am guessing that it has to be enclosed differently but I can't find anything specific on this problem.  The top line is when it worked with a regular lowercase password.  The secone line is how it is with the new password and it doesn't work.


How can I add a counter to a one-liner Get-Aduser?

$
0
0

Hello,

I typically have the need to 'list out' accounts, groups, etc. based on some criteria and store in a file.  I would also like to store the number of accounts, groups, etc. Im 'listing' in the file, say at the end of the file.  So in the case below, how would I add a counter which would tally the objects I find based on the query and pass along the pipeline, then store this value at the end or beginning of the file?

Get-aduser -Filter *  -SearchBase "OU=Users,OU=SomeOU,dc=Acme,dc=net" -property PasswordNeverExpires | Sort Surname | FT Surname, GivenName, SamAccountName | out-file MyUserAccts.txt


Thanks for your help! SdeDot

out-file issue;

$
0
0

hi I have a variable in this format
ServerA , DOMAIN\ACCOUNTA
ServerB,  DOMAIN\ACCOUNTB

Then finally i write to a file
$ServerNameAndServiceAccount | Out-File C:\DBA\ServersServiceAcct.txt -Append

When I open the file the format is like this

SERVERA

,
DOMAIN\ACCOUNTA

SERVERB

,
DOMAIN\ACCOUNTA

Any way not to add a newline when writing to a file using out-file?
When I open the file I want to see it like this
ServerA , DOMAIN\ACCOUNTA
ServerB,  DOMAIN\ACCOUNTB
Thanks

How to output to a file

$
0
0

How can I output the script to a file?

foreach ($usr in Get-ADUser -Filter ({enabled -eq $true -and mail -like "*"}) -Properties mail) { Get-InboxRule -Mailbox $usr.mail | select $usr.name, name, description | fl  }


Jason

Weird problem with FileSystemWatcher

$
0
0

I'm having a really issue with the FileSystemWatcher in PowerShell. We have a large multifunction copier that employees scan to PDF's with. The machine will send the files to an FTP server. I've setup one on one of our servers. However, to prevent employees from uploading a file with the same name and overwriting an existing file, I have a PowerShell script which continuously monitors the FTP drop folder using the FileSystemWatcher and immediately moves any new file created into a different folder, renaming it if a file with that name already exists. It works great with every test EXCEPT the multifunction copier! When I scan to the FTP server, it doesn't trigger a file creation event. The file just sits in the drop folder. If I FTP manually from another computer and upload the file, it works fine. If I'm sitting in front of the server console and manually add a new file to the folder, it immediately moves it like it's supposed to. However, for some reason uploads from the copier won't trigger the event. I'm always using the same anonymous account for all the testing. I've tried two different FTP servers, the integrated IIS FTP in windows 2008 Server and FileZilla FTP Server. I'm using PowerShell 2.0. Thanks for any help you all can offer. Here's my code: (I know it has an infinite loop. I did this to keep it running continuously. If anybody has a better idea let me know. I have it set up in Task Scheduler and use that to start and stop it.)

# Specify the folder files are uploaded to
$drop_folder = 'E:\FTP Drop\Referral Denial'
$dest_folder = 'E:\Referral Denial\Drop'

# Create the FileSystemWatcher object
$fswatcher = New-Object IO.FileSystemWatcher
$fswatcher.NotifyFilter = [IO.NotifyFilters]'FileName'
$fswatcher.Path = $drop_folder
$fswatcher.EnableRaisingEvents = $true

# Register the Created ObjectEvent for a new file in $drop_folder
$onCreated = Register-ObjectEvent $fswatcher Created -SourceIdentifier FileCreated -Action {

 $filename = $Event.SourceEventArgs.Name
 
 # Check to see if the file name already exists in the destination folder.
 # If so, count the number of files starting with the file name.
 # Then append this count plus one to the end of the file.
 if (Test-Path $dest_folder\$filename)
 {
 
    # Get the base of the current file name
    $base_name = (Get-ChildItem $drop_folder\$filename).BaseName
    
    # Get the extension of the current file name
    $ext_name = (Get-ChildItem $drop_folder\$filename).Extension
    
    # Count the number of files starting with the current base file name in the destination folder
    $num_duplicates = @(Get-ChildItem $dest_folder -filter $base_name*.*).Count
    
    # Create the new file name
    $new_filename = ($base_name + '_(' + ($num_duplicates + 1) + ')' + $ext_name)
     
    # Rename the dropped file to the new file name
    Rename-Item $drop_folder\$filename $new_filename
    
    # Set the file name to the new file name
    $filename = $new_filename
    
 }
 
 # Move the dropped file into the destination folder
 Move-Item $drop_folder\$filename $dest_folder
 
}
 

# Loop forever until task scheduler terminates the script

while ($true)
{
    #Pause for 50ms to keep from using too much CPU
    start-sleep -milliseconds 50
}


Change default location of my profile (CurrentUserCurrentHost dir)

$
0
0

My documents is located on a network share (thus so is my default profile location). I want to change this to be local. i.e. run $profile | Select * I want to change the location of CurrentUserCurrentHost to be somewhere else.

Anyone know how to?

Thanks in advance!

Keith

Assigning Values to a Variable using Loop

$
0
0

Hi,

I have created variables using a loop based on a list of computers (looping through them).

While creating this variables i also create another set of variables in the same loop.

see below sample code:

cls
Get-Variable -Name "SRV_*" | Remove-Variable
Get-Variable -Name "Info_*" | Remove-Variable
$comps = "server01","server02","server03"
foreach($comp in $comps)
{
  New-Variable -Name "SRV_$Comp" -Value $Comp
  New-Variable -Name "Info_$Comp" -Value "GOOD"
  Get-Variable -Name "SRV_$Comp" | % {
  	
	# How to assign the value of $Info_<>  variables to $SRV_<> variables?
  }
}

how to assign the Srv_<> variables the value of Info_<> variables?

thanks for the help

Sort a list in powershell

$
0
0

I would like to sort the list $items by the 3 element $items[2] before it gets used in the foreach loop. how 
would I do this?

$items = $list.GetItems($query);

$stream = [System.IO.StreamWriter] "RoomBookingList.txt"
$stream.WriteLine("Start Time,End Time,Location,Contact,Meeting")

foreach ($item in $items)
{

  $title = $item[0];
  $location = $item[1];
  $start = $item[2];
  $end = $item[3];
   

$stream.WriteLine("$($starttime),$($endtime),$($location),$($contact),$($title)")
}

LF "if (userinput=ctrl+c) Stop-Transcript" syntax

$
0
0

Hi all, I'm new to powershell. I'm using 1.0 at work and just generating the test I run to an output example: test.ps1 > C:\test\log\test.txt

does not write all of the output from the powershell consol and is missing a lot of output needed to review after running a test.

After doing a little research I found I can add to the script the following

_____________________________________________________________

$ErrorActionPreference="SilentlyContinue" Stop-Transcript | out-null $ErrorActionPreference = "Continue" Start-Transcript -path C:\output.txt -append # do some stuff Stop-Transcript

_____________________________________________________

So the issue with this is if I need to stop the script by hitting ctrl+c in the consol, it does not stop the transcript to the file.

The only way I can think of getting it to stop transcript automatically is adding an if statement. I'm not sure about the syntacs though to check for the userinput for ctrl+c and need some help with this.

Burned out and know i am missing some simple syntax

$
0
0

I need 2 things from the think tank here :)

$ServerList = Get-ADComputer -Filter {OperatingSystem -Like "Windows *Server*"} -Property * | Select-Object Name
foreach ($Server in $ServerList)
{
      #Echo back current server
      write-host $server
      get-WmiObject -computer $Server -query "select Description from Win32_OperatingSystem" | select-object Description
      }

This is my script for pulling the description from the Description field on servers, not the one from AD.

If i use get-content instead of "$ServerList = Get-ADComputer -Filter {OperatingSystem -Like "Windows *Server*"} -Property * | Select-Object Name " it works fine but this comes out with trying to connect to

@{Name=Hostname}

and that doesn't work. So

#1 what is the syntax i need to get it to connect to the Hostname instad of the @{Name=Hostname} which it always fails to find

and/or

#2. If you can tell me how to output this to a csv or xls/xlsx file where the name/description comes out in pairs. I am just so burnt out right now trying to get this right and i know its staring me in the face.

Thanks for any and all help people may give.

Cannot index into a null array.

$
0
0

i have a powershell script that creates a Site Collection, SharePoint Permission Levels, SharePoint Groups and adds users to group
sequentially, enables the essential features in the Site Collection, uploads the master page, and the site template 

when i run the script it creates user groups with the names in a csv file attached and referred to also it gets the user names in each group from the same csv file i already added the users but when i run the script it returns the following error:

AD User ADMAPAPP\cma.administrator does not exists

Cannot index into a null array

At C:\ADSSC\Deployment\Application\CMA_Script.ps1:979 char:35

+ $groupexists = $weburl.SiteGroups[ <<<<  $line.GroupName]

+CategoryInfo                  :  InvalidOperation:  <CMA_Customer:String> [], RuntimeException

+FullyQualifiedErrorId : NullArray

How to run a Powershell script to automatically logon to Gmail under Google's Chrome?

$
0
0

I use Powershell to run a script to automatically logon to Gmail under Internet Explorer.

My grandaughter saw me use this and asked if she could get the same function on her PC done for Google's Chrome browser (her PC runs Windows XP and IE 8 is just too darn slow and a resource hog as well to run as her browser, so she runs Google's Chrome. I know, I know, I should get her a new PC, but maybe for Xmas, but meanwhile...).

Anyways, I'm too non-technical to be able to modify my Powershell script to make it work under Google's Chrome. Can anyone help me get this working for my grandaughter?

Here's the Powershell script that I use for the automatic logon to Gmail under Internet Explorer:

# Ensure that you are not already signed-in Gmail!
#seeking help to improve this script
$url = "http://gmail.com"
$username="Your_username"
$password="Your_password"
#$ie = New-Object -com internetexplorer.application;
#$ie.visible = $true;
#$ie.navigate($url);
$ie = New-Object -ComObject InternetExplorer.Application
$ie.Visible = $true
$ie.navigate($url);
$sw = @'
[DllImport("user32.dll")]
public static extern int ShowWindow(int hwnd, int nCmdShow);
'@
$type = Add-Type -Name ShowWindow2 -MemberDefinition $sw -Language CSharpVersion3 -Namespace Utils -PassThru
$type::ShowWindow($ie.hwnd, 3) # 3 = maximize
while ($ie.Busy -eq $true)
{
	Start-Sleep -Milliseconds 1000;
}
$ie.Document.getElementById("email").value = $username
$ie.Document.getElementByID("Passwd").value=$password
$ie.Document.getElementById("signin").Click();
What do I need to do to modify this Powershell script for my grandaughter so that it automatically logs her on to Gmail under Google's Chrome instead of Internet Explorer?

how to create psobject with hidden properties?

$
0
0

when we run "gps" it shows us 8 columns of data for each process by default in a nice table format. but there are alot more hidden properties if you refer to "gps | gm"

i'd like to do the same thing when i create my own psobject. right now i have alot of properties so it always shows it in a list format instead of a nice table format cuz there's too many columns. i know i can do format-table and select only the ones i want to see but that would mean i have to get all the results first and then format it. my script runs async and outputs as the results come in so i don't want to have to use format-table cuz i want to show results as they come in.  it needs to retain the raw psobject i originally created so the user can then manipulate the data and filter as needed later. hard to explain so i'll explain below

$bigstuff New-Object PSObject -Property @{
LineNumber = 1
Date = 2
ServerName = 3
DatabaseName = 4
UserName = 5
CreateDate = 6
DateLastModified = 7
AsymMetricKey = 8
DefaultSchema = 9
HasDBAccess = 10
ID = 11
LoginType = 12
Login = 13
Orphan = 14
}


$smallstuff = New-Object PSObject -Property @{
LineNumber = 1
Date = 2
ServerName = 3
}

$bigstuff will show in list format by default. $smallstuff will show in table format. how do i create a psobject with the same data as $bigdata but only dispaly a small set of properties in table format without formatting the data with format-table. this is mainly for easy readability by default without forcing the user of my script to pipe it to format-table and select the properties they want to see. but before they can do that they will have to use get-member to see all properties if they forget so i just want to cut down on that by giving them what they want to see by default and allowing them to see more if they want.

after creating the object, i want to be able to just call the var $bigstuff and it only list 3 properties i specify to be default. but allow the user themselves to pass $bigstuff to format-table or other commands to manipulate the data themselves. so i need my script to maintain the raw psobject to allow this flexibility. hope that makes sense. thanks!


New Excel column based on data in another column

$
0
0
Hi

I am using Excel 2007. I have a list of 50 servers and their locations, including DR sites.

In ColumnA is the servername, in ColumnB is the 4 sites they can be located in, written in the format below as an example:

[LondonUK, 1] [ManchUK, 2] [GlasUK, 3] [ParisFrance, 4] [LyonFrance, 5]

What I'd like to do is have another two Columns in the sheet to represent

i. The primary location
ii. The third failover location

So essentially, ColumnC would be based on the value for the 1 location (in my example above its LondonUK), but I'm only concerned with the country, so I would like ColumnC to say

If 1 value contains *UK*, then ColumnC value should be UK
If 1 value contains *France*, then ColumnC should be France
If 1 value contains "Germ*, then ColumnC should be Germany

Likewise for the third failover location, but this time I'm using the 3 value.

Is this possible using Powershell?

Configure Auditing for a 'specific AD user object' for a 'specific AD user attribute' located in a 'specific OU' using PowerShell

$
0
0

Hi
Guys,

In this
link: http://support.microsoft.com/kb/814595, under
'Configure Auditing for Specific Active Directory Objects',
steps are provided that explain how to configure auditing for specific active
directory objects using GUI. However, I have thousands of users located under
multiple OUs on which I would like to audit only a certain AD attribute of a
specific user object. Hence, My goal is to come up with a PowerShell script
that, upon running as a scheduled task, will automatically configure auditing on
a specific "AD attribute" of a User object located in a certain OU. This AD
attribute could be 'manager'. The PowerShell script should be well written with
comments that easily allows me to add/remove/edit the auditing of certain AD
attributes of the User object located in a certain OU. Can somebody please help
me in writing this script or may be come up with this PowerShell
script?

For those
who wonder why I need to do this, here is the explanation. In the end, I intend
to generate an SCOM alert via this auditing that will identify that the previous
value of the 'manager' AD attribute of a specific user 'Henry' located in a
certain 'OU' with this distinguished name 'dn' was changed from a certain value
X to a certain value Y. I know already how to do this, but I am unable to come
up with the PowerShell script described above.

Thanks,

Faisal

Run more then 1, but not all at once

$
0
0

So i am running a command here. If i run -asjob all machine run at once which could be thousands which is to much. and if i take it out it runs one at a time which is to slow.

Would there be a way to convert this to run a number of machines at a time that i could adjust? 

$domaincomputers = "domain.forest.org/Computers"

$cred = get-credential

Get-QADComputer -SearchRoot $domaincomputers | %{Invoke-command ($_.name+ ".domain.forest.org") -cred $cred -auth credssp  -asjob  -scriptblock{

My command here

}

}


Supress returned value from PowerShell return statement

$
0
0

Hi,

I have a function that returns a variable. I want that variable to be suppressed by default when the function is called but the value should be available so that I can use it when assigning the function to a variable. How can I do that?

Example:

 ------What I have -------

Function Test {
$a = 10
return $a
}

>Test
10

>$out = Test
>$out
10



 -----What I want ------

>Test
<blank/supressed output>

>
>$out = Test
>$out
10

Viewing all 2562 articles
Browse latest View live


Latest Images

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