Quantcast
Channel: Windows PowerShell forum
Viewing all 21975 articles
Browse latest View live

Get return code from "second" powershell.exe in cmd

$
0
0

Im trying to get the errorcode from the "second" powershell process in cmd.

If I run this in cmd: powershell.exe -noprofile -command "&{ start-process -FilePath 'powershell.exe' -ArgumentList '-noprofile get-service' -verb RunAs}"

echo %errorlevel%  returns the value of the "first" powershell.exe.




Problems with a PS script

$
0
0

Complete novice on PS here.  however i have a script that i wrote to pull certain files off of windows 7 and windows 10 laptops.  The script works perfectly on windows 7 but not on windows 10.  The code i have is below:

    

$date = Get-Date -UFormat %m%d%Y

#Gets and assigns the drive letter for the backup destination, located on the USB drive.
$winpe = Get-WmiObject win32_logicaldisk -filter "VolumeName = 'WINPE'"
$servicetag = Get-WmiObject win32_bios
$tag = $servicetag.serialnumber
$a = $winpe.DeviceID
$dest = "$a\Backups\$tag-$date"

#Gets and assigns the drive letter for the Hard Drive.
$hdd = Get-WmiObject win32_logicaldisk -Filter "VolumeName = 'OSDISK'"
$d = $hdd.DeviceID

#If backup for current date has been created, stop script.  Else, backup files.
if (Test-Path $dest){
    Write-Host "Backup already completed." 
    break
    } else {

  cd $d

  I get an error on windows 10 that says "

cd : Cannot process argument because the value of argument "path" is null. Change the value of argument "path" to a non-null value.
At line:2 char:3
+   cd $d
+   ~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Set-Location], PSArgumentNullException
    + FullyQualifiedErrorId : ArgumentNull,Microsoft.PowerShell.Commands.SetLocationCommand

I'm assuming that it has something to do with changing the directory but it works fine on windows 7.  any help would be greatly appreciated.  t

 

Powershell running slowly on Win2019 compared to Win2016

$
0
0

Hi All, 

I have an issue where a script i have made takes about 10x longer to execute on windows 2019 than on a windows 2016 machine. 

Both machines are virtual and identically placed on the same host with the same configuration of ram,cpu,storage etc. 

Powershell version on 2019: 

5.1.17763.316 

Powershell version on 2016:

5.1.14393.2791 

This is what the script looks like, i have shortened it a bit to give this example. 

$UserFile = Import-Csv -delimiter "," -Path "C:\temp\UserFile.txt" -Encoding Default `

foreach ($User in $UserFile){

    $SSN = $user.SocialSecurityNumber
    $Samaccountname = $User.UserID
    $UserFirstname = $User.Firstname
    $UserLastname = $User.Lastname
    $Titel = $User.Title
    $ManagerSocialSecurityNumber = $user.Manager.substring(2)
    $ManagerSamaccountname = ($UserFile | Where-Object {($_.SocialSecurityNumber -eq $Manager)} | Select UserID).UserID

    }


I am importing a file with data every night which will enter the data in our AD. 

The file in question does not contain any information about the managers UserID in AD, so i am mapping the managers userID with this line here: 

$ManagerSamaccountname = ($UserFile | Where-Object {($_.SocialSecurityNumber -eq $Manager)} | Select UserID).UserID

Identical script running on Win2016 using Measure-command: 

Minutes           : 0
Seconds           : 12
Milliseconds      : 786

Same script running on Win2019 using Measure-Command

Minutes           : 2
Seconds           : 24
Milliseconds      : 121

Win2019 version: 

1809 (OS Build 17763.316)

Win2016 version: 

1607 (OS Build 14393.2791)

Does anyone know if there are some known bugs in powershell for Win2019 causing this issue? 

Or is this just some issue local to myself? 

Best regards

Joakim


4624 (logon) events followed closely by 4634 (logoff) events

$
0
0

Thank you for reading this.

From what I have read, DC logs show authentication times and not necessarily logon session times. I decided to query a workstation's logs for logon activity so that i can match the Logon ID values of logon and corresponding logoff times. I felt that if I could match a logon and logoff's logon IDs I would have a good idea of how long the session was active for. I even extracted the logon type as well so that I could focus on only Interactive (2) and RemoteInteractive (10) logons. I only decided to do this after seeing that just extracting and matching logon and logoff event times show that a user logs on and logs off like 2 to 20 seconds later.

However I didn't get different results. Every logon was far apart from the corresponding logoff by a maximum of 20 secs. I know I haven't been logging on and logging off  immediately for the past 20 days. See below for my code for logon and logoff.

Please help me figure this out. 

#logoff

$start = (Get-Date) - (New-TimeSpan -Days 24)
$end = (Get-Date) - (New-TimeSpan -Days 0)

Get-WinEvent -ComputerName computer1 -FilterHashTable @{LogName='Security'; ID=4634 ; StartTime= $start; EndTime= $end ;  Data="username"} |
where {($_.properties[4].value -eq 2) -or ($_.properties[4].value -eq 10)} | 
select timecreated, @{Name='SecurityId';Expression={$_.Properties[0].Value}}, `
                            @{Name='AccountName';Expression={$_.Properties[1].Value}}, `
                            @{Name='AccountDomain';Expression={$_.Properties[2].Value}}, `
                            @{Name='LogonId';Expression={$_.Properties[3].Value}}, `
                            @{Name='LogonType';Expression={$_.Properties[4].Value}} |
 export-csv -path C:\results\computer1Logoff.csv -NoTypeInformation


#logon

$start = (Get-Date) - (New-TimeSpan -Days 24)
$end = (Get-Date) - (New-TimeSpan -Days 0)

Get-WinEvent -ComputerName computer1 -FilterHashTable @{LogName='Security'; ID=4624 ; StartTime= $start; EndTime= $end ;  Data="username"} |
where {($_.properties[8].value -eq 2) -or ($_.properties[8].value -eq 10)} | 
select timecreated, @{Name='SecurityId';Expression={$_.Properties[4].Value}}, `
                            @{Name='AccountName';Expression={$_.Properties[5].Value}}, `
                            @{Name='AccountDomain';Expression={$_.Properties[6].Value}}, `
                            @{Name='LogonId';Expression={$_.Properties[7].Value}}, `
                            @{Name='LogonType';Expression={$_.Properties[8].Value}}, `
                            @{Name='Workstation';Expression={$_.Properties[11].Value}}, `
                            @{Name='LogonGuid';Expression={$_.Properties[12].Value}} |
 export-csv -path c:\results\computer1Logon.csv -NoTypeInformation

Output (after sorting in Excel to match Logon IDs. Some columns were removed from the logon version)



set-adUser from an SQL query

$
0
0

Hello There, 

interresting issue here !

I'm running an SQL query in PS and would like to update user information in AD from data in that table.

still a PS beginner so code might be ugly, sorry about that :) 

i have in my script the following (I'm skipping the connection part):

$query = ExecuteSqlQuery -sqlquery "select EMP_BIN,EMP_MAIL,EMP_Phone,EMP_Mobile,DIRECT_MANAGER_BIN from [testDB].[dbo].[HR_Oracle_View_test] where (emp_Bin like 'T%' or emp_Bin like 'S%') "


$Users = Get-ADUser -Filter * -Properties SamAccountName -SearchBase "OU=Users,OU=Office,OU=test,DC=test,DC=COM"


Foreach ($Line in $query) {
    $emp_Bin = $Line.EMP_BIN
    $Username = ($Users | Where {$_.SamAccountName -eq $emp_bin}).SamAccountName
    $Param = @{}
If ($Username){        $Param.Add('Identity',$Username)         }
If ($Line.EMP_MAIL){   $Param.Add('EmailAddress',$Line.EMP_MAIL) }
If ($Line.EMP_Mobile){ $Param.Add('mobile',$Line.EMP_Mobile)     }
If ($Line.EMP_Phone){  $Param.Add('OfficePhone',$Line.EMP_Phone) }
If ($Line.DIRECT_MANAGER_BIN) {$Param.Add('manager',$Line.DIRECT_MANAGER_BIN) }
    
    If ($Username) {Set-ADUser @Param; Write-Host "Set new attributes info for $Username"}    
} 

i'm getting this error :

Set-ADUser : Cannot bind parameter 'Manager'. Cannot convert value "" to type "Microsoft.ActiveDirectory.Management.ADUser". Error: "Invalid cast from 'System.DBNull' to 'Microsoft.ActiveDirectory.Management.ADUser'
."
At C:\Users\hbardawil-adm\Desktop\connecttodb.ps1:80 char:31
+     If ($Username) {Set-ADUser <<<<  @Param; Write-Host "Set new attributes info for $Username"}    
    + CategoryInfo          : InvalidArgument: (:) [Set-ADUser], ParameterBindingException
    + FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.ActiveDirectory.Management.Commands.SetADUser

i'm guessing maybe the data format in the sql table is wrong ? as this code works if i replace the sql query by a csv.

Cheers


Hitch Bardawil



Get-ADUser and concatenating a collection to a string

$
0
0

Hi there,

I am trying to extract some data from AD, and I need to transform the msRTPSIP-PrimaryUserAddress field from a collection into a delimited string. This works for most scenarios but it seems to take an exception to the - between msRTPSIP and PrimaryUserAddress in the expression. It is treating the - as syntax. I can't escape the - with the ` character and quoting it just treats it as text and not a property. Any ideas?

@{"name"="msRTPSIP-PrimaryUserAddress";"expression"={$_.msRTPSIP-PrimaryUserAddress}}

powershell to csv getting columns

$
0
0

Hi all,

For my internship I need to write a script. My script is: Get-ADUser -Filter * -Properties * | select Name,whenCreated, Description, whenchanged, Lastlogondate, LastBadPasswordAttempt, BadlogonCount, LockedOut, Enabled |export-csv c:\informatie-user-csv.csv.

how can I get all these properties in a different columns in my csv-file?

Greetings

Sam

Importing modules

$
0
0

Hi,

when you import a module using import-module, should the module then permanently be available to use next time you open powershell, because it just seemed like I had to reimport after a server restart.

Thanks.


Changing PS language supresses errors

$
0
0

Hi all.

I would like to change the language in this script to Norwegian, and believe I have done it successfully, however, this change has suppressed error messages that is output. The same issue is present with Using-Culture en-US

Any ideas on why this happens and how to fix it if possible?

My method of testing what the output error is, is by creating a new VPN connection with the same name as a existing one. Without the Using-Culture function, errors are shown. With it, the errors are supressed and the script only shows the custom message (Which is shown when a error is present regardless).

>The script adds a VPN connection based on Cisco Meraki default connections.

Below is a example that produces errors as normal:

try {
        $Name = Read-Host -Prompt 'Enter the profile name for this VPN connection'
        $password = Read-Host -AsSecureString "Please enter your Pre-shared Key"

        # Default Cisco Meraki parameters
        $password = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($password))
        Add-VpnConnection -Name "$Name" -ServerAddress 193.214.153.2 -AuthenticationMethod MSChapv2 -L2tpPsk "$password" -TunnelType L2tp -RememberCredential -Force

        # Gives popup with information on next steps
        $wshell = New-Object -ComObject WScript.Shell
        $wshell.Popup("VPN-profile for $Name has been created.`nYou may now use this connection.`nUsername and password is required on first time sign on.`nSupport: contact | company", 0, "Completed") | Out-Null
    } catch {
        # Reports error and supresses "Completed"
        Write-Error $_.Exception.ToString()
        Read-Host -Prompt "The above error occurred, please try again. If the issue persists, please contact support.`nSupport: contact | company`nPlease press Enter to exit"
    }

See below for the full script, in which the language change is implemented (I belive). 

Function Using-Culture([Globalization.CultureInfo]$culture, [ScriptBlock]$script) {
    $OldCulture = [System.Threading.Thread]::CurrentThread.CurrentCulture
    trap {
        [System.Threading.Thread]::CurrentThread.CurrentCulture = $OldCulture
    }
    [System.Threading.Thread]::CurrentThread.CurrentCulture = $culture
    $ExecutionContext.InvokeCommand.InvokeScript($script)
    [System.Threading.Thread]::CurrentThread.CurrentCulture = $OldCulture
}

Using-Culture nb-NO {
    try {
        $Name = Read-Host -Prompt 'Enter the profile name for this VPN connection'
        $password = Read-Host -AsSecureString "Please enter your Pre-shared Key"

        # Default Cisco Meraki parameters
        $password = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($password))
        Add-VpnConnection -Name "$Name" -ServerAddress 193.214.153.2 -AuthenticationMethod MSChapv2 -L2tpPsk "$password" -TunnelType L2tp -RememberCredential -Force

        # Gives popup with information on next steps
        $wshell = New-Object -ComObject WScript.Shell
        $wshell.Popup("VPN-profile for $Name has been created.`nYou may now use this connection.`nUsername and password is required on first time sign on.`nSupport: contact | company", 0, "Completed") | Out-Null
    } catch {
        # Reports error and supresses "Completed"
        Write-Error $_.Exception.ToString()
        Read-Host -Prompt "The above error occurred, please try again. If the issue persists, please contact support.`nSupport: contact | company`nPlease press Enter to exit"
    }
}

I have kept all the custom text that a user will see in English here, to hopefully help you assist me better.

Thanks in advance!

How to pull specific file extension across all the servers

$
0
0

Hi All,

Need your assistance here-

Request : I have 100 servers, where we take the backups with format Ex: XXX.BAK so I need to pull on all the serves

a)complete location of the files(it's name) where it resides- note it should even detect for the mount points as well.

b)Size should   be > 1GB and files should be older than 5days.

need the result in csv format like  name,sizeinGB,filelocation,date.

can some help on with the script,appreciated your help.


Regards, S_NO "_"

PowerShell Forms - Textbox Input Check - Forward Content to a new Form

$
0
0

Hello Everyone,

I am struggling with a form, in combination with a Textbox and data entered into it. I started to build a test script that works as shown in example 1 and then extended it and need to do some minor changes to make it work.

In example 1: I generate a Form, ask for a Name and after a data input and pressing OK, a second form opens to present the data in a label. That works fine and I would like to have it on such way.

CLS
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing

#New User Form
$TestForm = New-Object System.Windows.Forms.Form
$TestForm.Text = "Test Name Input"
$TestForm.AutoScroll = $True
$TestForm.AutoSizeMode = "GrowAndShrink"
$TestForm.MinimizeBox = $True
$TestForm.MaximizeBox = $True
$TestForm.WindowState = "Normal"
$TestForm.Size = New-Object System.Drawing.Size(1000,1000)
$TestForm.StartPosition = 'CenterScreen'


#New User Form Title
$TestFormTitle = New-Object System.Windows.Forms.Label
$TestFormTitle.Location = New-Object System.Drawing.Point(10,30)
$TestFormTitle.Size = New-Object System.Drawing.Size(450,50)
$TestFormTitleFont = New-Object System.Drawing.Font("Times New Roman",26,[System.Drawing.FontStyle]::Bold)
$TestFormTitle.Font = $TestFormTitleFont
$TestFormTitle.Text = "This is a Test"
$TestForm.Controls.Add($TestFormTitle)

#New User Form Label Firstname
$TestFormFormLabelFirstname = New-Object System.Windows.Forms.Label
$TestFormFormLabelFirstname.Location = New-Object System.Drawing.Point(10,100)
$TestFormFormLabelFirstname.Size = New-Object System.Drawing.Size(885,40)
$TestFormFormLabelFirstnameFont = New-Object System.Drawing.Font("Arial",16,[System.Drawing.FontStyle]::Italic)
$TestFormFormLabelFirstname.ForeColor = "DarkBlue"
$TestFormFormLabelFirstname.Font = $TestFormFormLabelFirstnameFont
$TestFormFormLabelFirstname.Text = "Please Enter Firstname"
$TestForm.Controls.Add($TestFormFormLabelFirstname)

#New User Form Textbox Firstname
$TestFormTextBoxFirstname = New-Object System.Windows.Forms.TextBox
$TestFormTextBoxFirstname.Location = New-Object System.Drawing.Point(10,140)
$TestFormTextBoxFirstname.Size = New-Object System.Drawing.Size(885,100)
$TestFormTextBoxFirstnameFont = New-Object System.Drawing.Font("Arial",20,[System.Drawing.FontStyle]::Italic)
$TestFormTextBoxFirstname.Font = $TestFormTextBoxFirstnameFont
$TestForm.Controls.Add($TestFormTextBoxFirstname)

#Create OK Button
$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Point(190,860)
$OKButton.Size = New-Object System.Drawing.Size(200,75)
$OKButton.Font = New-Object System.Drawing.Font("Arial",16,[System.Drawing.FontStyle]::Regular)
$OKButton.Text = 'OK'               
$OKButton.DialogResult = [System.Windows.Forms.DialogResult]::OK           
$TestForm.AcceptButton = $OKButton
$TestForm.Controls.Add($OKButton)           


$result = $TestForm.ShowDialog()

#Confirmation Name Form
$ConfirmatonNameform = New-Object System.Windows.Forms.Form
$ConfirmatonNameform.Text = "Confirmation Name"
$ConfirmatonNameform.Size = "1300, 780"
$ConfirmatonNameform.StartPosition = "CenterScreen"
$ConfirmatonNameform.Icon = $ConfirmatonNewUserformIcon
$ConfirmatonNameform.AutoSize = $False
$ConfirmatonNameform.BringToFront()

#Confirmation New User Firstname Label
$ConfirmatonNameLabel = New-Object System.Windows.Forms.Label
$ConfirmatonNameLabel.Location = New-Object System.Drawing.Point(10,80)
$ConfirmatonNameLabel.Size = New-Object System.Drawing.Size(200,50)
$ConfirmatonNameLabelFont = New-Object System.Drawing.Font("Times New Roman",18,[System.Drawing.FontStyle]::Regular)
$ConfirmatonNameLabel.ForeColor = "DarkBlue"
$ConfirmatonNameLabel.Font = $ConfirmatonNameLabelFont
$ConfirmatonNameLabel.Text = "Firstname:"
$ConfirmatonNameform.Controls.Add($ConfirmatonNameLabel)

#Confirmation New User Firstname Data
$ConfirmatonNamevar = New-Object System.Windows.Forms.Label
$ConfirmatonNamevar.Location = New-Object System.Drawing.Point(400,80)
$ConfirmatonNamevar.Size = New-Object System.Drawing.Size(700,50)
$ConfirmatonNamevarFont = New-Object System.Drawing.Font("Times New Roman",18,[System.Drawing.FontStyle]::Regular)
$ConfirmatonNamevar.ForeColor = "Black"
$ConfirmatonNamevar.Font = $ConfirmatonNamevarFont
$ConfirmatonNamevar.text = $TestFormTextBoxFirstname.text
$ConfirmatonNameform.Controls.Add($ConfirmatonNamevar)



if ($result -eq [System.Windows.Forms.DialogResult]::OK)
{$ConfirmatonNameform.ShowDialog()}

I have extended this form and because I have several Textboxes, I wanted to have a mechanism, to prevent a textbox left-out without any data entered.

In example 2 you can see how the code looks slightly different.

CLS
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing

#New User Form
$TestForm = New-Object System.Windows.Forms.Form
$TestForm.Text = "Test Name Input"
$TestForm.AutoScroll = $True
$TestForm.AutoSizeMode = "GrowAndShrink"
$TestForm.MinimizeBox = $True
$TestForm.MaximizeBox = $True
$TestForm.WindowState = "Normal"
$TestForm.Size = New-Object System.Drawing.Size(1000,1000)
$TestForm.StartPosition = 'CenterScreen'


#New User Form Title
$TestFormTitle = New-Object System.Windows.Forms.Label
$TestFormTitle.Location = New-Object System.Drawing.Point(10,30)
$TestFormTitle.Size = New-Object System.Drawing.Size(450,50)
$TestFormTitleFont = New-Object System.Drawing.Font("Times New Roman",26,[System.Drawing.FontStyle]::Bold)
$TestFormTitle.Font = $TestFormTitleFont
$TestFormTitle.Text = "This is a Test"
$TestForm.Controls.Add($TestFormTitle)

#New User Form Label Firstname
$TestFormFormLabelFirstname = New-Object System.Windows.Forms.Label
$TestFormFormLabelFirstname.Location = New-Object System.Drawing.Point(10,100)
$TestFormFormLabelFirstname.Size = New-Object System.Drawing.Size(885,40)
$TestFormFormLabelFirstnameFont = New-Object System.Drawing.Font("Arial",16,[System.Drawing.FontStyle]::Italic)
$TestFormFormLabelFirstname.ForeColor = "DarkBlue"
$TestFormFormLabelFirstname.Font = $TestFormFormLabelFirstnameFont
$TestFormFormLabelFirstname.Text = "Please Enter Firstname"
$TestForm.Controls.Add($TestFormFormLabelFirstname)

#New User Form Textbox Firstname
$TestFormTextBoxFirstname = New-Object System.Windows.Forms.TextBox
$TestFormTextBoxFirstname.Location = New-Object System.Drawing.Point(10,140)
$TestFormTextBoxFirstname.Size = New-Object System.Drawing.Size(885,100)
$TestFormTextBoxFirstnameFont = New-Object System.Drawing.Font("Arial",20,[System.Drawing.FontStyle]::Italic)
$TestFormTextBoxFirstname.Font = $TestFormTextBoxFirstnameFont
$TestForm.Controls.Add($TestFormTextBoxFirstname)

#Create OK Button
$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Point(190,860)
$OKButton.Size = New-Object System.Drawing.Size(200,75)
$OKButton.Font = New-Object System.Drawing.Font("Arial",16,[System.Drawing.FontStyle]::Regular)
$OKButton.Text = 'OK'               
$TestForm.AcceptButton = $OKButton
$TestForm.Controls.Add($OKButton)           

#Check if Name has been entered
$OKButtonClickEvent = (
    {if (!$TestFormTextBoxFirstname.text -and !$TestFormTextBoxFirstname.text -eq 'True') {[System.Windows.MessageBox]::Show('No data entered in Firstname','Ooops','OK','Warning')}
            Else {$TestForm.Hide(),$ConfirmationNameform.ShowDialog()}
    }
)

$OKButton.Add_Click($OKButtonClickEvent) 
$TestForm.ShowDialog()


#Confirmation Name Form
$ConfirmationNameform = New-Object System.Windows.Forms.Form
$ConfirmationNameform.Text = "Confirmation Name"
$ConfirmationNameform.Size = "1300, 780"
$ConfirmationNameform.StartPosition = "CenterScreen"
$ConfirmationNameform.Icon = $ConfirmationNewUserformIcon
$ConfirmationNameform.AutoSize = $False
$ConfirmationNameform.BringToFront()

#Confirmation New User Firstname Label
$ConfirmationNameLabel = New-Object System.Windows.Forms.Label
$ConfirmationNameLabel.Location = New-Object System.Drawing.Point(10,80)
$ConfirmationNameLabel.Size = New-Object System.Drawing.Size(200,50)
$ConfirmationNameLabelFont = New-Object System.Drawing.Font("Times New Roman",18,[System.Drawing.FontStyle]::Regular)
$ConfirmationNameLabel.ForeColor = "DarkBlue"
$ConfirmationNameLabel.Font = $ConfirmationNameLabelFont
$ConfirmationNameLabel.Text = "Firstname:"
$ConfirmationNameform.Controls.Add($ConfirmationNameLabel)

#Confirmation New User Firstname Data
$ConfirmationNamevar = New-Object System.Windows.Forms.Label
$ConfirmationNamevar.Location = New-Object System.Drawing.Point(400,80)
$ConfirmationNamevar.Size = New-Object System.Drawing.Size(700,50)
$ConfirmationNamevarFont = New-Object System.Drawing.Font("Times New Roman",18,[System.Drawing.FontStyle]::Regular)
$ConfirmationNamevar.ForeColor = "Black"
$ConfirmationNamevar.Font = $ConfirmationNamevarFont
$ConfirmationNamevar.text = $TestFormTextBoxFirstname.text
$ConfirmationNameform.Controls.Add($ConfirmationNamevar)


The ClickEvent (thanx jrv) checks if data has been entered and if not, will give a warning. This also works perfectly and I was happy but then, I faced a new problem:

As soon as the second form opens, for some reason, the content of the textbox in the example called "$TestFormTextBoxFirstname.text" is empty.

What I was able to find out is, that if I run the Script a second time, I get the UserInput from the first try and if I understand correctly, that means, that the name entered in example 2 and stored as a variable, runs through without being forwarding to the second form to "$ConfirmationNamevar.text". I was playing around, trying different approaches but was not able to fix it.

I tried this approach, because I had no clue, how to show "$TestFormTextBoxFirstname.text" directly in the Label. Here,  I also tried several ways but failed also.

What am I doing wrong? Can someone help with a solution, so I can keep the ClickEvent and have the content of the Textbox transferred into the Second Form, so the name is shown, as it works correctly in example 1?

Thank you very much for your help,

Mike

automate Send As Permissions

$
0
0

Hello

I'm trying to create a PowerShell Script that will connect to Exchange Online and prompt to apply Send As Permissions for an Exchange Online mailbox for on premise shared mailbox. I have got far as connecting to Exchange Online but not really sure how to add the script after this. I would expect a prompt to ask for the 'Shared Mailbox name' and 'Exchange Online User' UPN.

Any help / pointers will be appreciated.

add-RecipientPermission <sharedmailboxname> -AccessRights SendAs -Trustee Usermailbox@domain.com

try
{
write-Host "Connecting to Exchange Online"
$UserCredential = Get-Credential
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUrihttps://outlook.office365.com/powershell-liveid/ -Credential $UserCredential -Authentication Basic -AllowRedirection
Import-PSSession $Session -DisableNameChecking
}
catch
{
write-host " Can't Connect to Exchange Online, make sure you have the correct module installed"
PAUSE
break
}

Replacing all addresses in proxyaddresses with array

$
0
0

we have local AD that synchronizes to O365

we are adding a new email address with new domain to all users in two phases.

1) add new email address and let settle.

2) make new email address the primary email address (smtp: -> SMTP:)

I have a script I found where everything seems to work until the last command:

Set-ADUser -identity $UserName -Replace @{ProxyAddresses=$NewProxyAddresses}

The error I get with this command is:

Invalid type 'System.Management.Automation.PSObject'.
Parameter name: ProxyAddresses
    + CategoryInfo          : InvalidArgument: (user:ADUser) [Set-ADUser], ArgumentException
    + FullyQualifiedErrorId : Invalid type 'System.Management.Automation.PSObject'.
Parameter name: ProxyAddresses,Microsoft.ActiveDirectory.Management.Commands.SetADUser

The output of $NewProxyAddresses is:

smtp:user@olddomain.com
smtp:user@domain.com
X400:C=us;A= ;P=Company;O=Exchange;S=surname;G=givenname;
SMTP:firstlast@newdomain.com

The output of the $newProxyAdderesses is correct, but I am unable to run the set-aduser command


Is it possible to read/write excel files using OpenXML & PowerShell?

$
0
0

Hello Experts,

We are planning to automate some of the tasks at server side where MS Office is not installed. Hence we have installed Open XML SDK. Unfortunately I didn't find any helpful info to read/write excel files using open XML & PowerShell.

Please let me know for any documentation or examples.

Thanks in advance.

Regards,

Bulk update for .onmicrosoft smtp

$
0
0

Hello, 

I was trying to help a co-worker correct some addresses but didn't have the necessary knowledge to assist.

We've been scripting the New User Creation to add accounts to our Active Directory for syncing to exchange.

My account is currently formatted correctly with nathan.allen@company.onmicrosoft.com


Starting around September of last year the script was updated to include additional features but has been producing accounts with the below formatting:


the smtp for the .onmicrosoft address has been being set to first.last_company.com@company.onmicrosoft.com

Is there a scripting procedure we could use to bulk update this to match my account? We have added a ton of new users and this has only just now been noticed. It appears whoever made the changes to the newuser script foresaw a conflict if the onmicrosft smtp had two '@' symbols but it's also possible that the '_' is being added automatically somewhere else in the process to evade that conflict.

Attempting to change this from Exchange will not work, it must be done on-premises through the directory. There was some concern this may require some form of Linux code but I'm not aware enough of the potential complications as I'm primarily involved with UI based functions and have limited knowledge. I'll do my best to gather any more information you might need to help.

I would provide pictures of a correctly formatted vs incorrectly formatted account but my technet user account is not verified yet.

Appreciate your suggestions.


Input Variable

$
0
0

I’ve got an input variable called DatabaseInput.

I would like to get all the subfolders from a folder location and use a substring function to remove the datestamp from the folder and match it to my input variable (DatabaseInput)

Example of the folder structure: Database1_20190221171833

I would like to remove the datestamp from the folder., however my code is bombing out. Please help!

Code below:

#Get all child items of the root backup folder
$BackupMounts = Get-ChildItem -Force $RestorePath | Where-Object { ($.Name -like “B1”) -or ($.Name -like “B2”)}

ForEach ($backupMount in $BackupMounts) {
(’------backupMount: ’ + $backupMount) | Out-File $SQLOutputFile -append
$RestorePath = “\xxxx\Backups” + $backupMount
(’------Restore Path: ’ + $RestorePath) | Out-File $SQLOutputFile -append

$databaseFolders =Get-ChildItem -Force $RestorePath"\Backups" | Where-Object { ($.Name -like “Database1*”) -or ($.Name -like “Database2*”) -or ($.Name -like “Database3*”) -or ($.Name -like “Database4*”) -or ($.Name -like “Database5*”) -or ($.Name -like “Database6*”) -or ($.Name -like “Database7*”) -or ($.Name -like “Database8*”) -or ($.Name -like “Database9*”)} | % {$.Name} | Sort -descending

#$databasefolders = Get-ChildItem -Force $RestorePath"\Backups" | Where-Object {($.Name -like $databasefolders.substring(0,($databasefolders.length -15)) -eq $DatabaseInput)} | % {$.Name} | Sort -descending

Start-Job and Invoke-Command jobs running as ps v1?

$
0
0

Any way I can force the background jobs to run as my current powershell version (v5.1).  This outputs the same with Invoke-Command -AsJob as well.  I think I'm missing something stupid.

start-job -ScriptBlock {Get-host | Select-Object Version}

Receive-Job -id 286 Version RunspaceId ------- ---------- 1.0.0.0 6b69377d-5156-4708-8273-e9f34ed4e7af


Trying to get my powershell script for app pools listed on remote servers result to export to a csv

$
0
0

I have a neat powershell file which goes through a list of remote servers that has iis and outputs the result with server name, iis app pool names, dot net version, account identity etc and whether its started or not. It works to a t. Except no matter what i do, i cant export the result to a csv in a neat little format.  I have tried everything from export-csv, out-file, nothing works. I have to manually copy paste. Can someone help me get last bit of code so i can get the the result exported to a csv file..

# Get the remote server names

$computers = Get-Content "C:\Users\mxs67\Desktop\script\servers.txt"


#Running the invoke-command on remote machine to run the iisreset


foreach ($computer in $computers) 
{
       Write-Host "Details from server $computer..."

       Invoke-command  -ComputerName $computer  -ScriptBlock{

       # Ensure to import the WebAdministration module

            Import-Module WebAdministration
            $webapps = Get-WebApplication
$list = @()
foreach ($webapp in get-childitem IIS:\AppPools\)
{
$name = "IIS:\AppPools\" + $webapp.name
$item = @{}
$item.server = $computer
$item.WebAppName = $webapp.name
$item.Version = (Get-ItemProperty $name managedRuntimeVersion).Value
$item.State = (Get-WebAppPoolState -Name $webapp.name).Value
$item.UserIdentityType = $webapp.processModel.identityType
$item.Username = $webapp.processModel.userName
$item.Password = $webapp.processModel.password

$obj = New-Object PSObject -Property $item
$list += $obj
}

$list | Format-Table -a -Property "server","WebAppName", "Version", "State", "UserIdentityType", "Username", "Password"

}

}

Updating user's manager from CSV

$
0
0

Hi all,

I am currently trying to update the manager field from a CSV for our employees.

In my source CSV I have the following fields -

Emp Code,Username,Known as name,Surname,First name,Department,Division,Section,Team,Role,Work Area,Cost Centre,Start Date,End Date,Manager,ManagerEmpCode

I have existing code where I am updating other fields within the CSV that is working fine.

# Import AD Module             
Import-Module ActiveDirectory            
# Import CSV into variable $userscsv            
#$userscsv = import-csv             
$users = Import-Csv -Path C:\Scripts\ADUPLOADtest2.csv            
# Loop through CSV and update users if the exist in CSV file            
foreach ($user in $users) {            
#Search in specified OU and Update existing attributes            
 Get-ADUser -Filter "SamAccountName -eq '$($user.Username)'" -Properties * |            
  Set-ADUser -employeeNumber $($user.'Emp Code'); -extensionAttribute4 $($user.'Cost Centre'); -title $($user.Role); -Department $($user.'Work Area') 
  }

However I need assistance with linking and replacing the users manger with the one from the CSV.

I have the managers employee code and full name as shown above.

Any ideas?

Thank in advance

Brett

Start-Process to install .exe file

$
0
0

I am trying to install a .exe file and passing an ID and Key to activate it

$a = file.exe

$b = "id-value"

$c = "key-value"

Start-Process $a -ArgumentList ' id=`"$b`"  key=`"c`" /qn /norestart ' -Wait -PassThru

but i can make the install manually by .\file.exe id="id-value" key="key-value"

What is the best way to execute the .exe file and pass some parameters at the same <g class="gr_ gr_269 gr-alert gr_gramm gr_inline_cards gr_run_anim Punctuation multiReplace" data-gr-id="269" id="269">time.</g>

Viewing all 21975 articles
Browse latest View live


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