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

Powershell While/Until

$
0
0

Probably a simple answer but...

Writing a simple script to test connectivity to a device. I need it to loop back and  ask for another name of the connection fails OR let me know if it was successful.

If you have a successful attempt on the 1st try I cannot get it to write the verification. If it fails the 1st time, it will work perfect... le sigh

Here is what I have:

$GET_DEVICE_NAME = Read-Host "Please enter the device you verifing connection to"
$testConnection = Test-Connection $GET_DEVICE_NAME -Quiet

while($testConnection -eq $false)
{ Write-Host "Unable to locate  $GET_DEVICE_NAME Please verify name and connectivity."
  do{
  $GET_DEVICE_NAME = Read-Host "Please enter the device you are backing up"
    }
  Until($testConnection=Test-Connection $GET_DEVICE_NAME -Quiet)
  if($testConnection -eq $true)
  {
  Write-Host "$GET_DEVICE_NAME connection is verified"    
  break;}
}


Powershell and SQLconnection

$
0
0
I want to use the SQLConnection object as I would from vb, for example.  I'd like to do this:

e.g.

$conn = New-Object system.data.sqlclient.sqlconnectionstringbuilder

$conn.DataSource = 'myserver'




but this fails:

Keyword not supported: 'DataSource'.At line:1 char:4+

$conn. <<<< DataSource = 'myserver'

    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException

    + FullyQualifiedErrorId : PropertyAssignmentException


even though:

    PS C:\WINDOWS\system32\WindowsPowerShell> $conn|Get-Member *sour*

       TypeName: System.Data.SqlClient.SqlConnectionStringBuilder

    Name       MemberType Definition

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

    DataSource Property   System.String DataSource {get;set;}




My Powershell version:

    PS C:\WINDOWS\system32\WindowsPowerShell> $PSVersionTable

    Name                           Value
    ----                           -----
    CLRVersion                     2.0.50727.3634
    BuildVersion                   6.0.6002.18111
    PSVersion                      2.0
    WSManStackVersion              2.0
    PSCompatibleVersions           {1.0, 2.0}
    SerializationVersion           1.1.0.1
    PSRemotingProtocolVersion      2.1

What is causing the error message?

Specifically, this works: 

    $conn.database = 'mydb' 

(and sets the property 'InitialCatalog') 

 and this fails 

    $conn.initialcatalog = 'mydb' 

even though: 

    PS C:\WINDOWS\system32\WindowsPowerShell> $b|Get-Member initialcatalog 


    TypeName: System.Data.SqlClient.SqlConnectionStringBuilder 

    Name MemberType Definition 
    ---- ---------- ---------- 
    InitialCatalog Property System.String InitialCatalog {get;set;} 

What I'm confused about is why I can set the "database" property even though it's not in the member list, but I cannot set the properties in the member list, even though PS says that they are set-able.

All users and the OU they are in

$
0
0

so when i run 

 get-aduser -filter * -Properties * | select-object samaccountname,memberof

powershell displays back 

x.visitor                                                                 {CN=Guests,CN=Builtin,

which is what i want, but when i export it to excell i get 

x.visitorMicrosoft.ActiveDirectory.Management.ADPropertyValueCollection

how do i get it export the samaccountname and the OU it belongs to, i need this for all users. 

Task Scheduler with PowerShell - Task completed with Return code 0

$
0
0

Hi,

We have on Task scheduler job to run powershell script but it is always completed with return code 0 and not running the script. We have execution policy on the server is Unrestricted

Following is the Action set for the Powershell script.

1. Start a Program

2. C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe

3 -NoProfile C:\Script\XXX.ps1

Can any one please suggest in to this?

Regards,

Sapan Shah

PowerShell script to list user access with MemberOf for a specific OU

$
0
0

Hello,

I am trying to find the correct syntax to correct the following script so that it will only include the groups in a specific OU, instead of all the groups shown in the "MemberOf" tab.  Currently the script provides most of the correct information I need but includes all the groups in the "MemberOf" tab. I just need to list the groups from a specific OU, i.e Sample Security\Enterprise

Get-aduser –filter * -Properties DisplayName, Title, Manager, Department, Memberof | Select DisplayName, Title, Manager, Department, @{name=”MemberOf”;expression={$_.memberof -join “;”}} | Export-csv c:\Temp\UserAccess.csv

Any help would be appreciated.

Thanks,

Roger


Need to show mailbox name against each iteration of foreach being run against mailboxes - Powershell

$
0
0

Hi all, I'm pretty new to this so apologies in advance if I embarrass myself! I'm trying to get a list of all room mailboxes and whether a service account has Impersonation Rights to it or not. We have a Service Account that has Application Impersonation rights so I'm running the following;

$Rooms = get-mailbox | where {$_.recipienttypedetails -eq "RoomMailbox"}

Foreach ($Room in $Rooms) 

{

Get-ManagementRoleAssignment -GetEffectiveUsers | Where {$_.RoleAssigneeName -eq "RC SRV"}

}

But all I get is;

Name                           Role              RoleAssigneeName  RoleAssigneeType  AssignmentMethod  EffectiveUserNam
                                                                                                      e
----                           ----              ----------------  ----------------  ----------------  ----------------
impersonationassignmentname    ApplicationImp... RC SRV            User              Direct            RC SRV
impersonationassignmentname    ApplicationImp... RC SRV            User              Direct            RC SRV
impersonationassignmentname    ApplicationImp... RC SRV            User              Direct            RC SRV 

etc, a line for every Resource Mailbox we've got.

I've tried (among other things) adding 

$RoomName = $Rooms.Alias
write-output $RoomName

But it just lists every room against each output. I'm struggling and would really appreciate some help guys, my own investigating isn't turning much up, mainly because I don't think I know enough about scripting to know what to look for!

Thanks in advance....


Vbs script to open a website, auto input user Id and password

$
0
0

By reading few website, tried the below vbs code and I am unsuccessful.

It opens website but does not pick the name,

DIM IE
DIM ipf

Set IE = CreateObject("InternetExplorer.Application")
IE.navigate "

https:
//bsa.
bomag.
com/default/

"

IE.Visible = True

While IE.Busy
     WScript.Sleep 50
Wend

Set ipf = IE.document.all.getElementByID("Username")
ipf.Value = "redmond" 'fill in the text box
'Set ipf = IE.document.all.state
'ipf.Value = "WA" 'fill in the text box
'Set ipf = IE.document.all.Submit
'ipf.Click    'click the submit button
'IE.Quit

Requesting to review my website and correct my code, so that on click it can website.

regards


How to get a list of OU paths from Active Directory

$
0
0

Hi,

I could use some help with ideas for writing a script that will give me a list of all Active Directory paths that end in 'OU=Computers'. Here is an example:

OU=Computers,OU=Aberdeen,OU=PNW,DC=usa,DC=com (returning distinguished name is preferred)

This will end up with a fairly long list in our environment after the script inspects all available OUs that end with Computers. I'm not looking for a complete solution but some coaching would be greatly appreciated!

Thank you!

Rob


Script that uses EWS to create a top-level folder and then create sub-folders in the top-level folder?

$
0
0

Exchange 2010 SP2, Windows 2008 R2. I have been playing with EWS in hopes that I can meet the goals my client would like to achieve.  For newly created mailboxes, I need to create a root-level folder which contains several sub-folders. I have been able to script the creation of a SINGLE folder and I need assistance with the sub-folder creation. Here is the script I am using to create the parent folder and if you could please tell me what I need to add in order to create multiple sub-folders.

function CreateFolder($MailboxName)
{
    #Change the user to Impersonate
    $service.ImpersonatedUserId = new-object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress,$MailboxName);

    #Create the folder object

 $oFolder = new-object Microsoft.Exchange.WebServices.Data.Folder($service)
    $oFolder.DisplayName = $FolderName

    #Call Save to actually create the folder
    $oFolder.Save([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::msgfolderroot)

    $service.ImpersonatedUserId = $null
}

#Change the name of the folder
$FolderName = "My Custom Folders"
Import-Module -Name "C:\Program Files\Microsoft\Exchange\Web Services\1.2\Microsoft.Exchange.WebServices.dll"

$service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService([Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010_SP2)

# Set the Credentials
$service.Credentials = new-object Microsoft.Exchange.WebServices.Data.WebCredentials("username","password","domain")

# Use AutoDiscover
$UseAutoDiscover = $true
$a = get-mailbox "alias"

$a | foreach-object {
    $WindowsEmailAddress = $_.WindowsEmailAddress.ToString()

    CreateFolder($WindowsEmailAddress)
}

Getting issue while Exporting Azure API

$
0
0

Hi,

I am trying to export Azure API in Swagger format. Below is my script for same. Previously it was working very well. Currently when i run the script again, i am getting the error.

Script -

#variables
$path = "W:\Fiverr\API_tool\export-import"
$subscriptionid = "XXXXXXXXXXXXXXXXXXXXX"
$resourcegroup = "XXXX"
$servicename = "XXXXXX"
$APIIDpath = "$path\APIID"
$apiPATH = "$PATH\api"
$PRODUCTPATH = "$PATH\PRODUCT"
$POLICYpath = "$path\policy"
$namedvalues = "$path\namedvalues"
$operations = "$path\operations"

#import-module
get-module -Name azure* -ListAvailable | Import-Module

#Connecting to Azure Subscription
#Connect-AzureRmAccount  -Subscription $subscriptionid
$ApiMgmtContext = New-AzureRmApiManagementContext -ResourceGroupName $resourcegroup -ServiceName $servicename

#Export API
$ApiMgmtContext = New-AzureRmApiManagementContext -ResourceGroupName $resourcegroup -ServiceName $servicename
$APIS = Get-AzureRmApiManagementApi -Context $apimgmtcontext | Out-GridView -Title " API Selection " -passthru
$apis | export-csv $APIIDpath\apidetails.csv -NoTypeInformation
foreach ( $api in $apis ){ $name = $api.name                                               
                           $id = $api.apiid
						   echo $name-$id
                           try { Export-AzureRmApiManagementApi -Context $ApiMgmtContext -ApiId $id -SpecificationFormat Swagger -SaveAs "$APIpath\API_$id.swagger" -ErrorAction Stop }
                           catch { $a = $_.exception }
                           #exportPolicy
                           #scope= API-scope policy
                           Get-AzureRmApiManagementPolicy -Context $ApiMgmtContext -ApiId $id -SaveAs "$policypath\API_policy_$id.xml" -Force
						   $APIoperation = Get-AzureRmApiManagementOperation -Context $ApiMgmtContext -ApiId $id 
						   foreach ($oper in $APIoperation) {
						   echo "OperationID - $($oper.OperationId)"
						   echo "-----------------------------------"
								 Get-AzureRmApiManagementPolicy -Context $ApiMgmtContext -ApiId $id -OperationId $($oper.OperationId) -SaveAs "$operations\API_operation_$id-$($oper.OperationId).xml" -Force
							}
}

Error is at line

try { Export-AzureRmApiManagementApi -Context $ApiMgmtContext -ApiId $id -SpecificationFormat Swagger -SaveAs "$APIpath\API_$id.swagger" -ErrorAction Stop }
                           catch { $a = $_.exception 

But I am getting exception message

Retrieve only the InterfaceIndex integer from "Get-NetIPConfiguration"

$
0
0

Hi 

Can you please help me how I can retrieve just the integer, in this case 5?

//marsk

PS C:\instdir\script> $InterfaceIndex = Get-NetIPConfiguration | select -Property InterfaceIndex
PS C:\instdir\script> $InterfaceIndex

InterfaceIndex
--------------
             5


Martin Skorvald Elevation AB

How do I put back my VPS close pop up window notification that tells me that I am about to close my VPS ?

$
0
0
How do I put back my VPS close pop up window notification that tells me that I am about to close my VPS ?

launch CMD from powershell as network service and run the commands

$
0
0

Hi,

i need your help on one of my powershell script. i need to launch the CMD as "network service" and run some of the commands on the launched cmd without the interaction(not by manual typing).

psexec -i -u "nt authority\network service" cmd.exe 

the above code will launch the cmd as network service but wait for the other commands to type.

i am just a beginner to powershell , can someone please help me on this.

script for move file from volume to another MS2016server

$
0
0
good afternoon

I have a server with MS WIN2016Server. by capacity a new volume was added (vol F :) and a copy of the folders and permissions of the Vol E was made: al vol F :. when reviewing some folders the files that were copied have a weight of 0k in the destination, but in the origin if it is correct. Manually copy some folders and the files move correctly. How could I validate these folders that the files have a weight of 0k and overwrite them with the correct file using powershell

Issue with Batch scripting - dsadd user and commas

$
0
0

Hello,

I am trying to create an user and put it in a OU that has a comma in its name. Like so:

@echo off

for /f "tokens=1-5 delims=;" %%A in (users.txt) do (dsadd user "CN=%%A,OU=%%C,DC=%%D,DC=%%E" -pwd %%B)

pause

The "users.txt" file:

J.Martinez;Qwerty$123;"House, Flats, Condos";TEST;lan

So when i launch the script i get the following error message:

DSADD fails with: Value for 'Target object for this command' has incorrect format

And if i don't put quotes around the %%C, i get this one:

"Flats, " is an unknown parameter.

All the items in the txt file are from a csv file. There can be several dozen lines at a time and commas everywhere that we need to keep...

Plz halp...



Running Remote File.bat with parameters - not working?

$
0
0

Greetings,

I've been trying for a couple of days to figure out how this work...

i've tried the following methods to run a specific bat file on a remote machine:

Invoke-Command -ComputerName <Name> -ScriptBlock {& 'Path\File.bat -Parameter'}

Invoke-Command -ComputerName <Name> -ScriptBlock {& 'Path\File.bat'} -ArgumentList '-Parameter'

Anyone has any idea?

Best Regards,

Slyfer.

how to add addional /Regional clock( UK , UAE, Srilanka, Singapore time zone) to machine ussing group policy/ or Logon script/

$
0
0

Hi Team,

Happy Christmas!!

Please help me to add additional clock using group policy in client machine.

i have 100++ windows 7 machine where i want to add 4 more time zone .

I have followed the below link but bad luck.

http://dennisspan.com/configuring-regional-settings-and-windows-locales-with-group-policy/

Please help me to get any kind of logon script where i can add 4 time zone .

I have tried this command but its replacing one time zone only   Tzutil /s  "timezone"

Kindly assist .





Import User Setting into Active Directory

$
0
0

Hi

First i have to admit that my native language isn't English so sorry for any vocabulary and grammar mistakes in advance .

I'm new in Windows Server and i have a problem with it which is as follows : 

i have 900+ users in my active directory and i chose Log on Restriction in Account Tab when i was creating my users . 

and now i have situation which i have to add a new user to all of my user's log on setting . and for 900+ users , it's really difficult . so i wanted to know is there anyway to handle this issue using a script or something like that ? 

Thanks in advance 

declare first day in last month

$
0
0

Hi Team,

Can some help me how to declare first day in last month in powershell 

Exporting and Importing a site including nintex

$
0
0

Dear all,

I am normally not the developer, but the technical farm consultant for SharePoint farms.  Recently, one of the developers who are no longer available wrote a script to export and import site collections that also include nintex workflows.  By the"ExportSite" function, I am stuck as it does not run this function.  When it goes to run the rest, it generates an error that the filename doesn't exist.  Can someone help me with the "ExportSite" function?  See code:

#Add sharepoint pssnapin if it doesnt exist:
if ( (Get-PSSnapin -Name microsoft.sharepoint.powershell -EA "SilentlyContinue") -eq $null )
{
    Add-PsSnapin microsoft.sharepoint.powershell
}


function ExportSite{
    $filepath = $Title -replace '[\W]', ''
    write-host "Preparing all Nintex workflows for export..." -ForegroundColor Green
    $SourceSite = Get-SPSite -Identity $URL_Source
    $webs = Get-SPWeb -Site $SourceSite -Limit All
    foreach($web in $webs){
        $SourcewebURL = $web.url
        Write-Host "Preparing Nintex workflows on site $SourcewebURL" -ForegroundColor yellow
        NWAdmin -o preparesiteforexport -SiteUrl $SourcewebURL
    }
    Write-Host "Exporting new site $title..." -ForegroundColor Green
    Export-SPWeb -Identity $URL_Source -Path $ExportLocation\$filepath -IncludeUserSecurity -IncludeVersions All
    Write-Host "Export of site $title finished. The export file are on location $ExportLocation" -ForegroundColor Green
}

function ImportSite{
    $filepath = $Title -replace '[\W]', ''
    Write-Host "Creating new site $title..." -ForegroundColor Green
    New-SPSite -Url $URL_Target -OwnerAlias $OwnerAlias
    Write-Host "Importing new site $title..." -ForegroundColor Green
    Import-SPWeb -Identity $URL_Target -Path $ExportLocation\$filepath.cmp -ActivateSolutions -IncludeUserCustomAction All -IncludeUserSecurity -UpdateVersions Overwrite
    $Target_Site = Get-SPSite -Identity $URL_Target
    Write-Host "Restoring all Nintex workflows on all webs..." -ForegroundColor Green
    $webs = Get-SPWeb -Site $TargetSite -Limit All
    foreach($web in $webs){
        $TargetwebURL = $web.url
        Write-Host "Restoring Nintex workflows on site $TargetwebURL" -ForegroundColor yellow
        NWAdmin.exe -o FixSiteAfterImport -siteUrl $TargetwebURL
    }
    Write-Host "Site $title is now available on $URL_Target" -ForegroundColor Green
}


$title = "Sitecollectionname"
$URL_Source= "http://sitecollection"
$URL_Target= "http://sitecollection2"
$ExportLocation= "<Drive>:\export"
$OwnerAlias= "DOMAIN\user"

#ExportSite
ImportSite

Thank you in advance,

Blue

Viewing all 15028 articles
Browse latest View live


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