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

Shameless request: convert Groovy script to PowerShell

$
0
0

Hi all,

I'm submitting a shameless appeal to anyone who can convert my Groovy script to PowerShell.  I need to launch a process from a script that calls java.exe with some arguments.  I have the script done in Groovy, but the process is hanging for some reason which I'm currently investigating.

Since I'm going to be running this from within SQL Server Agent as a job, one of the options is to use PowerShell.  Since my script is pretty easy, I figured I'd see if anyone who knows both Groovy & PowerShell can translate for me.

Thanks in advance if you're willing to help!

 

// launches batching-bar-loader for the current date by default

import java.text.SimpleDateFormat

// set to false to skip actual process execution
def execute = true

def formatter = new SimpleDateFormat('yyyy-MM-dd')
formatter.timeZone = TimeZone.getTimeZone('UTC')
def sep = System.getProperty("file.separator")
// default current working directory to that of this script
def cwd = new File(getClass().protectionDomain.codeSource.location.path).parent
def cwdOption = "-cwd="
def jar = "my-app.jar"
def appConfig = "app-config.xml"
def jobId = "myJobId"
def tradingDate, startDateTime, endDateTime
def preArgs = ""
def postArgs = ""

if (!args) {
  usage()
  return -1
}

args?.each {
	if (it.startsWith('-D') || it.startsWith('-X')) {
		preArgs = "$preArgs $it"
	}
  else if (it.startsWith('tradingDate=')) {
    tradingDate = it
  }
  else if (it.startsWith('startDateTime=')) {
    startDateTime = it
  }
  else if (it.startsWith('endDateTime=')) {
    endDateTime = it
  }
  else if (it.startsWith(cwdOption)) {
    cwd = it.size() <= cwdOption.size() ? '.' : it[cwdOption.size()..-1]
  }
  else if (it.equalsIgnoreCase('-noexec')) {
    execute = false
  }
  else {
    postArgs = "$postArgs $it"
  }
}

if (cwd[-1] != sep) {
  cwd = "$cwd$sep"
}

startDateTime = startDateTime ?: ""
endDateTime = endDateTime ?: ""
tradingDate = tradingDate ?: ""

if (!(tradingDate || startDateTime || endDateTime)) tradingDate = "tradingDate=${formatter.format(new Date())}"

def cmd = "java $preArgs -jar $cwd$jar $appConfig $jobId $tradingDate $startDateTime $endDateTime $postArgs"

if (execute) {
  def process = cmd.execute(null, new File(cwd))
  process.waitFor()
	
  return process.exitValue()
}
else {
  println "executing [$cmd] in dir [$cwd]"
}

def usage() {
  println "Usage: TODO"
}

sorting of files, get-childitem

$
0
0

Hi, I'm trying to create a variable with a list of some .txt files in a folder, sorted alphabetically:

$txtfiles = Get-ChildItem "$Path\*.*" -include *.txt -name | Sort name -desc

The strange thing is when i echo this variable I don't get the files sorted the way I want:

echo $txtfiles
201210212000_file.txt
201210222000_file.txt
201210192000_file.txt
201210202000_file.txt

How can I change this to sort it right?

Thanks in advance.

Change File Attributes get-childitem And disable attributes of files

$
0
0

hello,

I want a script to reset the Files Attributes to Normal instead of Archive for particular files in a Directory.

Any help?

How to -replace text which contains > ?

$
0
0

Why next script doesn't work correctly? :

	$S = [String]
	$S = '00 05:57:14.763,115,<?query --FETCH API_CURSOR0000000001D5D546--?>,DMRWP,NULL,0,0,NULL,39,'
	Write-Host "## Before: $S"
	$S = $S -replace ('--?>,' , '--?>",')
	Write-Host "## After : $S"

Because it produces next output:

## Before: 00 05:57:14.763,115,<?query --FETCH API_CURSOR0000000001D5D546--?>,DMRWP,NULL,0,0,NULL,39,
## After : 00 05:57:14.763,115,<?query --FETCH API_CURSOR0000000001D5D546--?>,DMRWP,NULL,0,0,NULL,39,

But correct output should be:

## Before: 00 05:57:14.763,115,<?query --FETCH API_CURSOR0000000001D5D546--?>,DMRWP,NULL,0,0,NULL,39,
## After : 00 05:57:14.763,115,<?query --FETCH API_CURSOR0000000001D5D546--?>",DMRWP,NULL,0,0,NULL,39,


__________________________________________________________ If isn't above described anything, the following applies: Technical details: * OS: Windows Server v2008-R2, English, Enterprise Edition, x64, SP1 ** My User-Account is member of 'Administrators' local security group. * MS-SQL-Server: v2008-R2, English, Enterprise Edition, x64, SP1 ** My User-Account is member of 'SysAdmin' db-role.

Active Directory Passing a variable fails

$
0
0

Hi,

I am running the following commands and getting the error below, this appears that either i'm passing the wrong information or im not declaring the variable correctly. Could someone inform me how to resolve my error.

Purpose of this script is to get a list of users in all groups in the domain.

$ADGroup = Get-ADGroup -LDAPFilter "(&(objectCategory=group)(groupType:1.2.840.113556.1.4.803:=-2147483640))"
get-adgroupmember $ADGroup
Get-ADGroupMember : Cannot convert 'System.Object[]' to the type 'Microsoft.ActiveDirectory.Management.ADGroup' required by parameter 'Identity'. Specified me
thod is not supported.
At line:1 char:18
+ get-adgroupmember <<<<  $Groups
    + CategoryInfo          : InvalidArgument: (:) [Get-ADGroupMember], Parame
   terBindingException
    + FullyQualifiedErrorId : CannotConvertArgument,Microsoft.ActiveDirectory.
   Management.Commands.GetADGroupMember

Thanks in advanced for your help

Kind Regards,

Jason Field.

Find users from a field attribute in CSV list and output results

$
0
0

Can anyone point me in the right direction for creating a script for the following;

I have a excel spreadsheet sent each month with a list of leavers one of the columns is the payroll number which we use in the AD and input into the "Company" field under the Organisation tab. Is it possible to read this column (either direct from excel or if a just list the payroll numbers in a CSV file) and output any that are found in the AD?

PowerShell Weird .Count Behaviour!

$
0
0

Hello,

I'm getting weired random results from PowerShell. Here is the code:

$UserName = "Test.Test10"
$MatchingUsers = Get-Recipient -ANR "$UserName" | Where-Object {($_.RecipientType -eq "UserMailbox")}
$MatchingUsers.Count

When I execute the above code in Exchange Management Console, it sometimes works and sometimes not. i.e., The user named "Test.Test10" exists in Active Directory, but not contain mailbox. So it should result "0" for $MatchingUsers.Count.

I tried to log-in all several Mailbox servers directly and the cleared all sessions and even rebooted couple of lab servers. Still the result is same!

I'm not sure whether this a bug in Exchange side or in PowerShell or my code is incorrect! Any suggestions/help would be greatly appreciated. Thanks!

It works sometimes:

It won't sometimes:


Need timer to clear logs in continuous script

$
0
0

Hi, i have a script and it checks servers in the farm for high cpu and mem usage, im planing on running it continuously 24/7. I have it send an email if anything flagged and then log that in a file, i would like to clear this log file every hour.

The trouble is that this script is in a while loop and I cant seem to figure out how to incorporate a timer in this loop without it beeing set/reset everytime. Maybe something global i would need to set? Any ideas or help is appreciated.

Thanks


Get a list all users except Adminsitrator and krbtgt

$
0
0

Hi,

I'm using the following cmdlet to get a list of all users not logged on to Active Directory for 60 days. The only issue is that 'Administrator' and 'krbtgt' also get listed.

get-qaduser -inactive -DontUseDefaultIncludedProperties -include samaccountname -serializevalues -NotLoggedOnFor 60 -sizelimit 0 |
            Export-csv C:\Scripts\Exports\$(get-date -f yyyy-MM-dd_)inactive_user_accounts.csv

How can I exclude those two accounts from the export?

Thanks very much!

Powershell: OnFocus validate identity

$
0
0

I am building a form that will automate my companies computer builds a little better (SCCM doesn't do everything) and in order to make it "fat finger proof" I want to validate that the user id that is filled in is correct and depending on the validation, brings up a red X or a green check mark showing the user of the form that it is safe to move on. My problem is that while my script has no errors the proof of validation never shows. My script is over 2000 lines and proprietary but I hope that the snippet below is enough to help me. Thank you in advance!

$objTextBox = New-Object System.Windows.Forms.TextBox 
$objTextBox.Location = New-Object System.Drawing.Size(120,72) 
$objTextBox.Size = New-Object System.Drawing.Size(100,20)
$objTextBox.focus
({

$VerifyUser = Get-ADUser -LDAPFilter "(sAMAccountName=$userid)"

If ($VerifyUser -ne 'True') 
{
$objForm.Controls.Add($iderror)
}
Else {"Userid Found"}
}) 
$objForm.Controls.Add($objTextBox)

Renaming a user account to be zzz_OldUserName

$
0
0

Hi,

I'm trying to run the following Quest AD cmdlet to import a list of user accounts from a .csv file and rename those accounts to zzz_OldUserName:

"import-csv C:\Scripts\Exports\$(get-date -f yyyy-MM-dd_)inactive_user_accounts.csv | foreach{Get-QADUser $_.samaccountname | Disable-QADUser | Set-QADUser -UserPrincipalName "zzz$($_.userprincipalname)"}"

At the moment my test user just gets their loginname renamed to 'zzz'

Can anyone help me with formating that last variable?

Thanks very much!

read-host question

$
0
0

I am using the read-host command to have a user input his password to automatically map several network drives using the following command as an example

$password = Read-Host "Please enter your NT password"

is there a way so when the dialog box opens for him to type in his password instead of showing his password in plain text it hides it with stars or bullets or something?

Nested JSON within PowerShell

$
0
0

I'm having the hardest time trying to parse a nested JSON string.

Thanks in part to various posts, I've been able to create a completely bastardized solution:

Add-Type -Assembly System.Web.Extensions $url = "http://localhost/json.aspx" $web_string = (new-object System.Net.WebClient).DownloadString($url) $json = (new-object System.Web.Script.Serialization.JavaScriptSerializer).DeserializeObject($web_string) $body = "" foreach ($message in $json.messages) { write-host "$json.messages(0).row_id" # I wanted to make sure that $message has the correct variable }

However, when I run the script, this is what I get:

System.Collections.Generic.Dictionary`2[System.String,System.Object].messages(0).row_id
System.Collections.Generic.Dictionary`2[System.String,System.Object].messages(0).row_id

I can't seem to find a way to loop through each array within $json.messages.  Accessing the other objects work fine.  Am I missing a step?

Here's the source json:

{"time":"10/25/2012 11:03:03 AM",
 "nomail":"1",
 "messages":[ 
     {"row_id":"23",
      "message_from":"root@localhost",
      "subject":"Test",
      "addresses_count":"1"},
     {"row_id":"24",
      "message_from":"root@localhost",
      "subject":"Test with attachment",
      "addresses_count":"1"}
            ],
 "messages_processed":"2",
 "exit_code":"0"}

Thanks!


Looping through an Array and storing Random Numbers

$
0
0

I've tried different ways of storing random numbers into an array but I keep producing an error.  PS doesn't like $a[$x].  Is there another way of looping through an array and dropping in numbers?

Basicly I have something like this,

$x = 0

while ($x -le 10) {

     $a[$x] = Get-random -min 0 -max 9999

     $x++

}


MacrossVF1

GPO is not running poweshell using bat on Server WK3

$
0
0

Hi All

I have a W2k3 Server and have a bat file that has the following in it. - "Powershell.exe .\Localadminsetup.ps1"

In the same folder location I have a powershell script which is designed to create local admin accounts for all of our IT admins.

I have used the bat file file which is meant to run the following PS1 script to create these local passwords, however this doesn't work.

Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Force

$Computer = [ADSI]"WinNT://$Env:COMPUTERNAME,Computer"
$TestUser = $Computer.Create("User", "dpatwal")
$TestUser.SetPassword("Password*PW")
$TestUser.SetInfo()
$TestUser.FullName = "LOCAL ADMIN"
$TestUser.SetInfo()
$TestUser.UserFlags = 65536 
$TestUser.SetInfo()
$TestGroup = $Computer.Create("Group", "Administrators")
$TestGroup.SetInfo()
$TestGroup.Description = "Local Administrators"
$TestGroup.SetInfo()
$TestGroup.Add($TestUser.Path)
$Group = [ADSI]"WinNT://$Env:COMPUTERNAME/Administrators"
$Group.Add($TestGroup.Path)


$Computer = [ADSI]"WinNT://$Env:COMPUTERNAME,Computer"
$TestUser = $Computer.Create("User", "mwebb")
$TestUser.SetPassword("Password*PW")
$TestUser.SetInfo()
$TestUser.FullName = "LOCAL ADMIN"
$TestUser.SetInfo()
$TestUser.UserFlags = 65536 
$TestUser.SetInfo()
$TestGroup = $Computer.Create("Group", "Administrators")
$TestGroup.SetInfo()
$TestGroup.Description = "Local Administrators"
$TestGroup.SetInfo()
$TestGroup.Add($TestUser.Path)
$Group = [ADSI]"WinNT://$Env:COMPUTERNAME/Administrators"
$Group.Add($TestGroup.Path)


$Computer = [ADSI]"WinNT://$Env:COMPUTERNAME,Computer"
$TestUser = $Computer.Create("User", "dkirkman")
$TestUser.SetPassword("Password*PW")
$TestUser.SetInfo()
$TestUser.FullName = "LOCAL ADMIN"
$TestUser.SetInfo()
$TestUser.UserFlags = 65536 
$TestUser.SetInfo()
$TestGroup = $Computer.Create("Group", "Administrators")
$TestGroup.SetInfo()
$TestGroup.Description = "Local Administrators"
$TestGroup.SetInfo()
$TestGroup.Add($TestUser.Path)
$Group = [ADSI]"WinNT://$Env:COMPUTERNAME/Administrators"
$Group.Add($TestGroup.Path)


$Computer = [ADSI]"WinNT://$Env:COMPUTERNAME,Computer"
$TestUser = $Computer.Create("User", "jpearman")
$TestUser.SetPassword("Password*PW")
$TestUser.SetInfo()
$TestUser.FullName = "LOCAL ADMIN"
$TestUser.SetInfo()
$TestUser.UserFlags = 65536 
$TestUser.SetInfo()
$TestGroup = $Computer.Create("Group", "Administrators")
$TestGroup.SetInfo()
$TestGroup.Description = "Local Administrators"
$TestGroup.SetInfo()
$TestGroup.Add($TestUser.Path)
$Group = [ADSI]"WinNT://$Env:COMPUTERNAME/Administrators"
$Group.Add($TestGroup.Path)


$Computer = [ADSI]"WinNT://$Env:COMPUTERNAME,Computer"
$TestUser = $Computer.Create("User", "cmiller")
$TestUser.SetPassword("Password*PW")
$TestUser.SetInfo()
$TestUser.FullName = "LOCAL ADMIN"
$TestUser.SetInfo()
$TestUser.UserFlags = 65536 
$TestUser.SetInfo()
$TestGroup = $Computer.Create("Group", "Administrators")
$TestGroup.SetInfo()
$TestGroup.Description = "Local Administrators"
$TestGroup.SetInfo()
$TestGroup.Add($TestUser.Path)
$Group = [ADSI]"WinNT://$Env:COMPUTERNAME/Administrators"
$Group.Add($TestGroup.Path)


$Computer = [ADSI]"WinNT://$Env:COMPUTERNAME,Computer"
$TestUser = $Computer.Create("User", "lleigh")
$TestUser.SetPassword("Password*PW")
$TestUser.SetInfo()
$TestUser.FullName = "LOCAL ADMIN"
$TestUser.SetInfo()
$TestUser.UserFlags = 65536 
$TestUser.SetInfo()
$TestGroup = $Computer.Create("Group", "Administrators")
$TestGroup.SetInfo()
$TestGroup.Description = "Local Administrators"
$TestGroup.SetInfo()
$TestGroup.Add($TestUser.Path)
$Group = [ADSI]"WinNT://$Env:COMPUTERNAME/Administrators"
$Group.Add($TestGroup.Path)

Set-ExecutionPolicy -ExecutionPolicy Restricted -Force


WMI Win32_UserProfile Class

$
0
0
How does the Win32_UserProfile ChangeOwner method work? If I have a domain user log into a Windows 7 machine, and I want to point it to the old user profile, so that the user doesn't lose anything, can the ChangeOwner method in the userprofile class accomplish this? Or would I have to have the user log in, then log out, so I could log in myself as admin, and change the profileimagepath value in the new user SID to the old profile path.

WinForms need timer with refresh

$
0
0

Hi all

I have a code for citrix farm that calculates available licenses. That all works fine. I just want some sort of auto refresh incorporated, i tried using timer and do a button perform click type of thing, but realized that my timer runs only once without the whole while loop. Does anyone have any suggestions on this?

[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing") 
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") 
$Server = "ctxlcw8k1v"
$otherLicenses = "385"
$Pool = Get-WmiObject -class "Citrix_GT_License_Pool" -Namespace "ROOT\CitrixLicensing" -ComputerName $Server
# Calculate licenses in use, total number of licenses and percentage currently in use  
$InUse = ($Pool | Measure-Object -Property InUseCount -sum).Sum
$Installed = (($Pool | Measure-Object -Property Count -sum).Sum) - $otherLicenses
$Percentage = [math]::round(($InUse/$Installed)*100,2)
$left = $installed-$inuse
$objForm = New-Object System.Windows.Forms.Form 
$objForm.Text = "Citrix Licenses Count"
$objForm.Size = New-Object System.Drawing.Size(300,200) 
$objForm.Font = New-Object System.Drawing.Font("Times New Roman", "11")
$objForm.StartPosition = "CenterScreen"
$objForm.KeyPreview = $True
$objForm.Add_KeyDown({if ($_.KeyCode -eq "R") 
    {$RefreshButton.PerformClick()}})
$objForm.Add_KeyDown({if ($_.KeyCode -eq "C") 
    {$objForm.Close()}})
    
$objLabel = New-Object System.Windows.Forms.Label
$objLabel.Location = New-Object System.Drawing.Size(20,40) 
$objLabel.Size = New-Object System.Drawing.Size(280,20) 
$objLabel.Text = "Licenses left: $left/$installed (In use: $percentage%)"
$objForm.Controls.Add($objLabel) 
$RefreshButton = New-Object System.Windows.Forms.Button
$RefreshButton.Location = New-Object System.Drawing.Size(75,120)
$RefreshButton.Size = New-Object System.Drawing.Size(75,23)
$RefreshButton.Text = "Refresh"
$RefreshButton.Add_Click({ 
$Pool = Get-WmiObject -class "Citrix_GT_License_Pool" -Namespace "ROOT\CitrixLicensing" -ComputerName $Server
$InUse = ($Pool | Measure-Object -Property InUseCount -sum).Sum
$Installed = (($Pool | Measure-Object -Property Count -sum).Sum) - $otherLicenses
$Percentage = [math]::round(($InUse/$Installed)*100,2)
$left = $installed-$inuse
$objLabel.Text = "Licenses left: $left/$installed (In use: $percentage%)"
$objForm.Refresh()})
$objForm.Controls.Add($RefreshButton)
$CloseButton = New-Object System.Windows.Forms.Button
$CloseButton.Location = New-Object System.Drawing.Size(150,120)
$CloseButton.Size = New-Object System.Drawing.Size(75,23)
$CloseButton.Text = "Close"
$CloseButton.Add_Click({$objForm.Close()})
$objForm.Controls.Add($CloseButton)
$objForm.Topmost = $True
$objForm.Add_Shown({$objForm.Activate()})
[void] $objForm.ShowDialog()

Thanks

Can you pass a variable to a SQL Script with invoke-sqlcmd?

$
0
0

So this may be a stupid question but is it possible to pass Powershell variable to a SQL Script for instance

$Datetime=Read-Host 'Enter Date'
$Datetime=$Datetime.trim()

$dbs=Invoke-Sqlcmd -ServerInstance $EDDSServer -Database EDDS -InputFile $CasesSQLPath -Variable $datetime

and this pass to a SQL variable such as

Declare @examineDate varchar(10)

SET @examineDate = 'Powershell variable'

I understand that you can pass variables using the -Query but I guess I am wondering if this works with -Input File and how that would be accomplished.

Cant pull more than 8000 groups from AD

$
0
0

am trying to pull all the groups from Active Directory, but am not able to pull more than 8000 groups.

Is there any setting which restricts this? or what is the way to pull all those AD groups?

Thanks in advance!

Accessing the user names of the group from shared folder

$
0
0

Hi,

The input for the powershell script is the shared folder path C:\Temp\Payroll and I could able to populate the groups of the directory as below with access rights.
EE\Domain Admins(Full Control),EE\AKOZLOWS(RW) ,EE\CFO_FinSy_GrpPayRoll_RW(RW)

 

But I am struggling to get list the usernames mapped under those groups.

My Expected output:      

EE\Domain Admins                      Full Control             
EE\AKOZLOWS                            RW        
                                                            Kozlowski, Anna    RW               
EE\CFO_FinSy_GrpPayRoll_RW   RW    
                                                           Celecia, Julie    RW    
       CFO_FinSy_GrpPayRoll_A    RW    
                                                           langelo, Jessica    RW
                                                           Ngen, Thpos    RW
        riker, Gardy    RW
        eewitt, Noedl    RW
        eeuyen, Hannfah    RW
        Kozlowski, Ang    RW

I have only used Get-Acl cmdlet in my script for getting the above mentioned group names.

Can anyone can help on populating usernames like my expected output.

Thanks in Advance


Viewing all 2562 articles
Browse latest View live


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